JavaScript中的for语句和for语句之间有什么区别?

本文翻译自:What is the difference between ( for… in ) and ( for… of ) statements in JavaScript?

I know what is for... in loop(it iterate over key), but heard the first time about for... of (it iterate over value). 我知道循环中的for... in是什么(它遍历键),但是第一次听说是关于for... of (它遍历值)。 I am confused with for... of loop. for... of循环感到困惑。 I didn't get adject. 我没有形容词。 This is the code below : 这是下面的代码:

var arr = [3, 5, 7];
arr.foo = "hello";

for (var i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (var i of arr) {
   console.log(i); // logs "3", "5", "7"
    //it is does not log "3", "5", "7","hello"
}

What I got is, for... of iterates over property values. 我得到的是, for... of遍历属性值。 then why it doesn't log(return) "3", "5", "7","hello" instead of "3", "5", "7" ? 那么为什么它不记录(返回) "3", "5", "7","hello"而不是"3", "5", "7"呢? but for... in loop iterate over each key ("0", "1", "2", "foo"). for... in循环遍历每个键(“ 0”,“ 1”,“ 2”,“ foo”)。 here for... in loop also iterate over foo key. 在这里for... in循环还可以遍历foo键。 but for... of not iterarte over value of foo property ie "hello" .Why it is like that? 但是对于...不能超过foo属性的值,即"hello"为什么会这样呢?

Long story in short: 总而言之:

here i console for... of loop. 在这里,我for... of循环控制台。 it should be log "3", "5", "7","hello" but here it logs "3", "5", "7" . 它应为日志"3", "5", "7","hello"但此处应记录为"3", "5", "7" Why ? 为什么呢

Example Link 范例连结


#1楼

参考:https://stackoom.com/question/1ysbB/JavaScript中的for语句和for语句之间有什么区别


#2楼

for in loops over enumerable property names of an object. for in循环遍历对象的可枚举属性名称。

for of (new in ES6) does use an object-specific iterator and loops over the values generated by that. for of (ES6中的新增功能)确实使用了特定对象的迭代器,并遍历了由其生成的值。

In your example, the array iterator does yield all the values in the array (ignoring non-index properties). 在您的示例中, 数组迭代器的确会产生数组中的所有值(忽略非索引属性)。


#3楼

I find a complete answer at : https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html (Although it is for type script, this is same for javascript too) 我在以下位置找到了完整的答案: https : //www.typescriptlang.org/docs/handbook/iterators-and-generators.html (尽管它是针对类型脚本的,但对于JavaScript也是如此)

Both for..of and for..in statements iterate over lists; for..offor..in语句都遍历列表; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated. 但是,迭代的值是不同的, for..in返回要迭代的对象上的键的列表,而for..of返回要迭代的对象的数字属性的值的列表。

Here is an example that demonstrates this distinction: 这是一个展示这种区别的示例:

 let list = [4, 5, 6]; for (let i in list) { console.log(i); // "0", "1", "2", } for (let i of list) { console.log(i); // "4", "5", "6" } 

Another distinction is that for..in operates on any object; 另一个区别是for..in可对任何对象进行操作; it serves as a way to inspect properties on this object. 它用作检查此对象属性的一种方式。 for..of on the other hand, is mainly interested in values of iterable objects. 另一方面, for..of主要关注可迭代对象的值。 Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values. 诸如Map和Set之类的内置对象implement Symbol.iterator属性,从而可以访问存储的值。

 let pets = new Set(["Cat", "Dog", "Hamster"]); pets["species"] = "mammals"; for (let pet in pets) { console.log(pet); // "species" } for (let pet of pets) { console.log(pet); // "Cat", "Dog", "Hamster" } 

#4楼

The for-in statement iterates over the enumerable properties of an object, in arbitrary order. for-in语句以任意顺序遍历对象的可枚举属性。

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype 该循环将迭代对象本身的所有可枚举属性以及对象从其构造函数的原型继承的那些属性

You can think of it as "for in" basically iterates and list out all the keys. 您可以将其视为“ for in”,基本上可以进行迭代并列出所有键。

var str = 'abc';
var arrForOf = [];
var arrForIn = [];

for(value of str){
  arrForOf.push(value);
}

for(value in str){
  arrForIn.push(value);
}

console.log(arrForOf); 
// ["a", "b", "c"]
console.log(arrForIn); 
// ["0", "1", "2", "formatUnicorn", "truncate", "splitOnLast", "contains"]

#5楼

For...in loop 对于...在循环中

The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition. for ... in循环通过消除计数逻辑和退出条件,改善了for循环的弱点。

Example: 例:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; 但是,您仍然必须处理使用索引访问数组值的问题,这很臭。 it almost makes it more confusing than before. 它几乎使它比以前更加混乱。

Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). 另外,当您需要向数组(或另一个对象)添加额外的方法时,for ... in循环会给您带来麻烦。 Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop. 因为for ... in循环遍历所有可枚举的属性,所以这意味着,如果将任何其他属性添加到数组的原型中,则这些属性也将出现在循环中。

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

Prints: 印刷品:

0 0

1 1个

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); function(){for(let i = 0; i <this.length; i ++){this [i] = this [i] .toFixed(2); } } }}

This is why for...in loops are discouraged when looping over arrays. 这就是为什么在循环数组时不鼓励for ... in循环的原因。

NOTE : The forEach loop is another type of for loop in JavaScript. 注意forEach循环是JavaScript中的另一种for循环。 However, forEach() is actually an array method, so it can only be used exclusively with arrays. 但是, forEach()实际上是一个数组方法,因此它只能与数组一起使用。 There is also no way to stop or break a forEach loop. 也没有办法停止或中断forEach循环。 If you need that type of behavior in your loop, you'll have to use a basic for loop. 如果您需要在循环中使用这种类型的行为,则必须使用基本的for循环。

For...of loop 对于... of循环

The for...of loop is used to loop over any type of data that is iterable. for ... of循环用于循环访问任何可迭代的数据。

Example: 例:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

Prints: 印刷品:

0 0

1 1个

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

This makes the for...of loop the most concise version of all the for loops. 这使得for ... of循环成为所有for循环中最简洁的版本。

But wait, there's more! 但是,等等,还有更多! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops. for ... of循环还具有一些其他优点,可修复for和for ... in循环的弱点。

You can stop or break a for...of loop at anytime. 您可以随时停止或中断for ... of循环。

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  if (digit % 2 === 0) {
    continue;
  }
  console.log(digit);
}

Prints: 印刷品:

1 1个

3 3

5 5

7 7

9 9

And you don't have to worry about adding new properties to objects. 而且您不必担心向对象添加新属性。 The for...of loop will only loop over the values in the object. for ... of循环只会循环遍历对象中的值。


#6楼

The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. for...in语句以任意顺序遍历对象的可枚举属性。 Enumerable properties are those properties whose internal [[Enumerable]] flag is set to true, hence if there is any enumerable property in the prototype chain, the for...in loop will iterate on those as well. 可枚举属性是内部[[Enumerable]]标志设置为true的那些属性,因此,如果原型链中有任何可枚举属性,则for...in循环也将在这些属性上进行迭代。

The for...of statement iterates over data that iterable object defines to be iterated over. for...of语句遍历可迭代对象定义要迭代的数据。

Example: 例:

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];

for (let i in iterable) {
  console.log(i); // logs: 0, 1, 2, "arrCustom", "objCustom"
}

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

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

Like earlier, you can skip adding hasOwnProperty in for...of loops. 像之前一样,您可以跳过在for...of循环中添加hasOwnProperty

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值