js中的伪数组是指:无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以通过遍历方法来遍历它们,典型的是函数的argument参数。
这次给大家带来js伪数组使用详解,js伪数组使用的注意事项有哪些,下面就是实战案例,一起来看一下。
在javascript中什么是伪数组?
伪数组(类数组):无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以对真正数组遍历方法来遍历它们。
1.典型的是函数的 argument参数,
2.像调用getelementsbytagname,document.childnodes之类的,它们都返回 nodelist对象都属于伪数组。
那么如何将伪数组转化为标准数组?
可以使用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); for(var i=0;i<arguments.length;i++){ sum +=arguments[i]; } return sum; } console.log(add(1,2,5,8));</script><body></body></html>
运行结果:
将伪数组转化为标准数组
<!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>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
以上就是js中什么是伪数组的详细内容。