[04]Web前端进阶—JS伪数组
js伪数组
- 一、伪数组的特点
- 二、伪数组
- 常见的伪数组
- 伪数组转真
- 三、最后
一、伪数组的特点
- 具有lenght属性
- 可以使用下标访问数据
- 不具有数组的方法,比如push( ),pop( )等
二、伪数组
本质上是一个对象,有index、length等属性,但是不能使用数组的方法,如foreach( )、filter( )、map( )、find( )、reduce()等方法,但是能够通过遍历数组的方式进行访问(for 循环)
常见的伪数组
- 字符串之类的
- 函数的arguments(参数)、
- 通过document.getElementByTagName( )等获得的元素集合
- key为0,1,2数字且有length的模糊性的对象
//1.字符串
let str = 'hello';
console.log(str.length);
console.log(str[1]);
//2.function的arguments对象
let fun = function(a,b,c){
//arguments是一个对象
console.log(arguments);//Arguments { 0: 1, 1: 2, 2: "123", … }
console.log(a+b);//3
}
fun(1,2,'123');
//3.含有length的"假"对象
let obj = {
length:2
}
console.log(obj.length);//有length
console.log(obj[1]);//undefined
obj[1] = 'hello';//这样就有obj[1];
console.log(obj);//{ 1: "hello", length: 2 }
伪数组转真
-
ES6中将伪数组转换为真数组:var arr = Array.from(arguments);即可使用数组的方法
-
ES5中将伪数组转换为真数组:var arr=Array.prototype.slice.call(arguments) 或 Array.prototype.slice.apply(arguments);
-
使用[].slice.call(arguments) 或 [].slice.apply(arguments)
-
var arr = Array.of(arguments)
-
var arr = new Array(arguments)
注意:是返回一个新的数组
//例
let obj = {
length:2
}
var arr = new Array(obj);
var arr1 = Array.from(obj);
var arr3 = Array.prototype.slice.call(obj);
var arr4 = Array.prototype.slice.apply(obj)
console.log(arr1);
console.log(arr3);
console.log(arr4);
三、最后
如若文章有误,作者虚心请教,谢谢阅读