Javascript中的类数组对象 (Array-like Object)

类数组

什么是类数组?

类数组对象 (Array-like Object) 是类似数组一样有length属性和索引属性的对象。例如:

const arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }

类数组这个概念有什么用?

因为类数组对象不是数组,为了按数组的方式处理,可以把类数组转换成真正的数组后使用。例如,使用Array.prototype.map()方法 或 作为apply()的参数。

类数组对象转换数组的方式

const arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 };
console.log(arrayLike);
//{ '0': 'a', '1': 'b', '2': 'c', length: 3 }

// ES5 写法一
const array1 = [].slice.call(arrayLike);
console.log(array1);
//[ 'a', 'b', 'c' ]

// ES5 写法二
const array2 = Array.prototype.slice.call(arrayLike);
console.log(array2);
//[ 'a', 'b', 'c' ]

// ES6
const array3 = Array.from(arrayLike);
console.log(array3);
//[ 'a', 'b', 'c' ]

常见的类数组

1. arguments

console.log(Array.isArray(arguments));
//false
console.log(arguments);
//node打印: {}
//chrome打印: Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
//因为arguments具有Symbol.iterator属性,所以它可以用扩展运算符(...arguments) 或 其他使用迭代器的方法

2. NodeList

//仅限浏览器中
const nodeList = document.querySelectorAll('*');
console.log(Array.isArray(nodeList));
//false

3. 字符串 String

const array = Array.from('abc');
console.log(array);
//["a", "b", "c"]

4. TypedArray

const typedArray = new Int8Array(new ArrayBuffer(3));
console.log(Array.isArray(typedArray));
//false

…待补充


其他

另外, {length:0} 是类数组的特殊情况,转换时可以执行成功,返回空数组[]。

console.log(Array.from({length:0}));
//[]
console.log(Array.from(''));
//[]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值