伪数组转为真正的数组~~

伪数组是什么?

 1.典型的是函数的 argument参数,
 2.像调用getElementsByTagName,document.childNodes之类的,它们都返回 NodeList对象都属于伪数组。

特性:

1.具有length属性

2.按索引方式存储数据

3.不具有数组的push,pop等方法

如何转为真正的数组呢?

可以使用Array.prototype.slice.call(fakeArray)将数组转化为真正的Array 对象。

如下:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>伪数组</title>  
</head>  
<script>  
    function add(){  
        var sum=0;  
        console.log(arguments instanceof Array);//可以判断下此时是不是真正数组,返回值为false;  
        console.log(arguments);//此时打印的是传入的参数1,2,5,8  
        var arguments=Array.prototype.slice.call(arguments);//将伪数组转化为标准数组  
        arguments.push(10);//此时就可以调用标准数组的方法  
        console.log(arguments instanceof Array);//可以判断下此时是不是真正数组,返回值为true;  
        console.log(arguments);//此时打印的是传入的参数,push之后的数组1,2,5,8,10  
        for(var i=0;i<arguments.length;i++){  
            sum +=arguments[i];  
        }  
        return sum;  
    }  
  console.log(add(1,2,5,8));  
</script>  
<body>      
</body>  
</html>  
原文地址:https://www.cnblogs.com/Mrs-pao/p/7992769.html