javascript 类数组和数组的区别,dom的类数组如何转换成数组

  1. 定义
    数组是一个特殊对象,与常规对象的区别:
    a. 当由新元素添加到列表中时,自动更新length属性
    b. 设置length属性,可以截断数组
    c. 从Array.protoype中继承了方法
    d. 属性为’Array’
    类数组是一个拥有length属性,并且他属性为非负整数的普通对象,类数组不能直接调用数组方法。
  2. 区别
    本质:类数组是简单对象,它的原型关系与数组不同
let arrayLike = {
	length: 10,
}
console.log(arrayLike instanceof Array); // false
console.log(arrayLike.__proto__.constructor === Array); // false
console.log(arrayLike.toString()) // [object Object]
console.log(arrayLike.valueOf());// {length: 10}

let array = []
console.log(array instanceof Array); // true
console.log(array.__proto__.constructor === Array); // true
console.log(array.toString()) // ''
console.log(array.valueOf());// []

  1. 类数练转换为数组
    转换方法
    a. 使用Array.from()
    b. 使用Array.prototype.slice.call()
    c. 使用Array.prototype.forEach()进行属性遍历并组成新的数组
    转投须知
    a. 转换后的数组长度由length属性决定。索引不连续时转换结果是连续的,会自动补位
let al1 = {
	length: 4,
	0: 0,
	1: 1,
	3: 3,
	4: 4,
	5: 5,
}
console.log(Array. from(al1)) //[0, 1, undefined, 3]
	b.仅考虑0或正整数的索引
let al2 = {
	length: 4,
	'-1': -1,
	'0': 0,
	a: 'a',
	1: 1,
}
console.log(Array.from(al2)); // [0, 1, undefined, undefined]
	c.使用slice转换产生稀疏数组
let al2 = {
	length: 4,
	'-1': -1, 
	'0': 0,
	a: 'a',
	1: 1,
}
console.log(Array.from(al2)); // [0, 1,empty*2]
  1. 使用数组方法操作类数组注意地方
let arrayLike2 = {
	2: 3,
	3: 4,
	length: 2,
	push:Array.prototype.push
}
//push操作的是索引值为length的位置
arrayLike2.push(1);
console.log(arrayLike2);// {2: 1, 3: 4, length: 2, push: f}
arrayLike2.push(2);
console.log(arrayLike2);// {2: 1, 3: 2, length: 2, push: f}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值