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>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
以上就是js中什么是伪数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号