美文网首页
将可遍历类型转成数组

将可遍历类型转成数组

作者: shirleyyu001 | 来源:发表于2017-05-26 23:02 被阅读0次
    1、使用扩展运算符(...)
    let a=document.querySelectAll('div'),
        b=[...a];
    console.log(a.constructor===NodeList); //true
    console.log(a.constructor===Array); //true
    
    备注:鉴于浏览器的兼容性,此方法需要babel转码。
    2、Array.prototype.slice.call
    var dom=document.querySelectorAll('div'),
        arr=Array.prototype.slice.call(dom);
    console.log(arr.constructor===Array);  //true
    
    3、使用for...of的方式
    var dom=document.querySelectorAll('div'),
        arr=[];
    for(var key of dom){
        arr.push(dom[key]);
    }
    console.log(arr.constructor===Array);  //true
    
    备注:鉴于浏览器的兼容性,此方法需要babel转码。
    4、将字符串转成字符数组
    var a='asdgghhkfdld';
    var b=a.split('');
    console.log(b.constructor===Array);  //true
    

    若需要去除字符串内的重复字符,可使用Set+...方法。

    相关文章

      网友评论

          本文标题:将可遍历类型转成数组

          本文链接:https://www.haomeiwen.com/subject/ihhffxtx.html