本文主要介绍了javascript伪数组用法,结合实例形式分析了伪数组的概念、功能、定义及简单使用方法,需要的朋友可以参考下,希望能帮助到大家。
在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将伪数组转换为标准数组的多种方法
javascript 伪数组实现方法_javascript技巧
js中将htmlcollection/nodelist/伪数组转换成数组的代码_javascript技巧
以上就是详解javascript伪数组用法的详细内容。