美文网首页大话前端让前端飞
把arguments变成数组的几种方法

把arguments变成数组的几种方法

作者: fenerchen | 来源:发表于2018-04-01 22:58 被阅读24次
   function toarray(){
    console.log(arguments);

    //法1
    var x=[].slice.apply(arguments);
    console.log(x)

    //法1变形
    var y=Array.prototype.slice.apply(arguments)
    console.log(y)

    //法1用call替换apply
    var z=Array.prototype.slice.call(arguments)
    console.log(z)

    //法2,遍历arguments,入数组
    var arr=[];
    for(var i=0;i<arguments.length;i++){
        
        arr.push(arguments[i]);
    }
    console.log(arr)
    //法3
    var m=Array.from(arguments);
    console.log(m)

}
toarray(1,2,3,4)

输出

NodeList转数组

一下代码主要是为Nodelist转换为数组准备的,在IE8及更早的版本,NodeList实现是一个COM对象,使用Array.prototype.slice.apply(nodes)会导致错误,必须使用遍历

 function convertToArray(nodes) {
            var arr = null
            try {
                arr = Array.prototype.slice.apply(nodes)
            } catch (ex) {
                var len = nodes.length
                arr=[]
                for (var i = 0; i < len; i++) {
                    arr.push(nodes[i])
                }
            }
            return arr
        }

测试

//html
 <div id="fight">加油</div>
//js
 function convertToArray(nodes) {
            var arr = null
            try {
                arr = Array.prototype.slice.apply(nodes)
            } catch (ex) {
                var len = nodes.length
                arr=[]
                for (var i = 0; i < len; i++) {
                    arr.push(nodes[i])
                }
            }
            return arr
        }
        var x = convertToArray(c)
        console.log(x)//[text]
        console.log(Object.prototype.toString.apply(x))//[object Array]

相关文章

  • 把arguments变成数组的几种方法

    输出 NodeList转数组 一下代码主要是为Nodelist转换为数组准备的,在IE8及更早的版本,NodeLi...

  • 数组去重4种方法

    怎么把类数组转换为数组? 数组去重4几种方法:

  • [].shift.call(arguments)

    [].shift.call(arguments) 把类数组对象转为数组对象,删除并拿到arguments的第一项。...

  • 类数组转化为数组

    模拟内置slice实现数组克隆 优化类数组转数组的代码:借用数组原型上的slice方法,将arguments转化为...

  • 类数组转化为数组

    类数组是具有length属性,但不具有数组原型上的方法。常见的类数组有arguments、DOM操作方法返回的结果...

  • JavaScript - 类数组对象与数组

    类数组对象 有length属性 属性名为正整数(对应于数组的索引) 没有数组的方法 例子: arguments D...

  • js中 类数组对象转化成数组对象的几种方法

    Array.prototype.slice.call(arguments) 原理是数组的slice()方法可以从已...

  • Java Arrays

    Arrays:用于操作数组的工具类。里面都是静态方法。 asList:将数组变成list集合。 把数组变成list...

  • vue学习

    arguments是实参的集合 arguments是类数组,即有数组的形式没有数组的功能 Object.assig...

  • 伪数组转数组实现方式

    伪数组转数组方法 伪数组也叫类数组。像函数中的arguments(箭头函数除外)或者 一组元素返回的集合。 有时操...

网友评论

    本文标题:把arguments变成数组的几种方法

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