【javascript学习指南】JavaScript伪数组用法实例分析

更新时间:2024-03-23    来源:网页配色    手机版     字体:

【www.bbyears.com--网页配色】

本文实例讲述了JavaScript伪数组用法。分享给大家供大家参考,具体如下:

在Javascript中什么是伪数组?

伪数组(类数组):无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以对真正数组遍历方法来遍历它们。

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

那么如何将伪数组转化为标准数组?

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

举个例子,利用伪数组实现不定参数求和问题.





伪数组

<script>
  function add(){
    var sum=0;
    console.log(arguments);
    for(var i=0;i



运行结果:

将伪数组转化为标准数组





伪数组

<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



运行结果:

本文来源:http://www.bbyears.com/wangyezhizuo/143729.html