浅拷贝和深拷贝 - 前置(三) - for...in 和 for...of 对比

  • 详情可以点击本篇的阅读原文~

在我们工作的时候,会不会 for...infor...of 傻傻分不清,这里我们讲解下这两者的区别:

无论是 for...in 还是 for...of 语句都是迭代一些东西,它们之间的主要区别在于它们的迭代方式。

for...in 语句以任意顺序迭代对象的可枚举属性。

for...of 语句遍历可迭代对象定义要迭代的数据。

上代码:

/**	
 * @name 区分	
 * @description for...of 和 for...in 的区别	
 */	
Object.prototype.objCustom = function() {};	
Array.prototype.arrCustom = function() {};	

	
const iterable = [3, 5, 7];	
iterable.foo = 'hello';	

	
for (let i in iterable) {	
  console.log(i);	
}	
// 0	
// 1	
// 2	
// foo	
// arrCustom	
// objCustom	

	
for (let i in iterable) {	
  if (iterable.hasOwnProperty(i)) {	
    console.log(i);	
  }	
}	
// 0	
// 1	
// 2	
// foo	

	
for (let i of iterable) {	
  console.log(i);	
}	
// 3	
// 5	
// 7

首先,由于继承和原型链的关系,每个对象将继承 objCustom 属性,并且作为 Array 的每个对象将继承 arrCustom 属性。

因此,对象 iterable 继承属性 objCustomarrCustom

iterable.__proto__ 可以查找到 arrCustomiterable.__proto__.__proto__ 可以查找到 objCustom

然后,再我们通过 for...in 遍历 iterable 对象时,会遍历其所有的可枚举属性。

这里不是记录 3、5、7 或者 hello,因为这些不是枚举属性,但是会记录数组索引以及 arrCustomobjCustom

for (let i in iterable) {	
  console.log(i);	
}	
// 0	
// 1	
// 2	
// foo	
// arrCustom	
// objCustom

接着,如果我们使用 hasOwnProperty() 来检查,那么会检查属于自己的枚举属性(而不是继承的)。

for (let i in iterable) {	
  if (iterable.hasOwnProperty(i)) {	
    console.log(i);	
  }	
}	
// 0	
// 1	
// 2	
// foo

最后,需要了解的是 for...of,该循环迭代并记录 iterable 作为可迭代对象定义的迭代值,即 3、5、7,而不是任何对象的属性。

640?wx_fmt=png 由 梁峻荣 采用 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议进行许可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值