javascript for vs for in vs vs for of depth

There are several loop statements in Javascript but in most cases everyone tends to use for statements because we usually deal with looping scenarios which consist of known conditions with counters or we just need to iterate through a list of data elements.

Javascript中有多个循环语句,但是在大多数情况下,每个人都倾向于使用for语句,因为我们通常要处理由已知条件和计数器组成的循环方案,或者只需要遍历数据元素列表即可。

Eg:- Making an array of numbers for given start and end.

例如:-为给定的开始和结束制作一个数字数组。

In this simple example starting and ending is clearly pre-defined also it is related with counters(going from start to end). Let’s look into types of for

在这个简单的示例中,开始和结束显然是预先定义的,它也与计数器(从开始到结束)有关。 让我们来看看为类型for

循环... (for loop…)

This is the well known basic for loop which is having the following format.

这是众所周知的基本for循环,具有以下格式。

for([initialExpression]; [endingCondition]; [incrementalExpression])
// repetitive statements...

Importantly, above expressions which reside inside for are optional. Basically this simple for loop’s repetitive statements will be executed until [endingCondition] returns false (if it is not provided Javascript assumes it as true in order to continue the execution of the loop). consider the following examples that demonstrate several situations of for loop…

重要的是,驻留在for中的上述表达式是可选的。 基本上,此简单的for循环的重复语句将一直执行,直到[endingCondition]返回false (如果未提供,则Javascript假定它为true才能继续执行循环)。 考虑以下示例,这些示例演示了for循环的几种情况…

/**
* Example - 01
* -------------------------------------+
* for loop without internal expressions.
* Output: 0 1 2
* -------------------------------------+
**/


let i = 0;


for(;;) {
  console.log(i++);
  if(i == 3) break;
}


/**
* Example - 02
* -------------------------------------+
* for loop with all types of internal-
* expressions (what we do mostly).
* Output: 5 6 7
* -------------------------------------+
**/




for(let i = 5; i <= 7; i++) {
  console.log(i);
}




/**
* Example - 03
* -------------------------------------+
* for loop without an internal incremental-
* expression..array A will be grown dynamically
* Output: 4 5 6 7 5 4 5 6
* -------------------------------------+
**/


let A = [4, 5, 6, 7, 5]
for(let i = 0; A.length < 8;) {
  A.push(A[i]);
  i++;
}


console.log(A);

循环中… (for-in loop…)

This type of for loop will iterate through properties of objects (if a particular property is enumerable). If an Array or String type variable is provided, indexes are taken as keys as usual. let’s check some examples…

这种类型的for循环将遍历对象的属性(如果可以枚举特定的属性)。 如果提供了ArrayString类型的变量,则照常将索引用作键。 让我们看看一些例子...

/**
* Example - 01
* -------------------------------------+
* for-in loop iterates throgh a JSON object
* Output: a: 1, b: 1
* -------------------------------------+
**/
let Obj = {
  a: 1,
  b: 2
}


for(let prop in Obj) {
  console.log(`${prop}: ${Obj[prop]}`);
}




/**
* Example - 02
* -------------------------------------+
* for-in loop iterates throgh an object
* Output: width height
* -------------------------------------+
**/


class Icon{
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
}


for(let prop in new Icon(128, 32)) {
	console.log(prop);
}

Above examples simply iterate through properties of objects. Indeed, we cannot clearly trust the order of the for-in type loop due to some cross-browser issues. Importantly, in order to get a property via for-in loop the specific property should be enumerable. consider the following example for non-enumerable properties..

以上示例只是简单地遍历对象的属性。 实际上,由于一些跨浏览器的问题,我们不能明确地信任for-in类型循环的顺序。 重要的是,为了通过for-in循环获取属性,应枚举特定属性。 考虑以下示例的不可枚举的属性。

/**
* Example - 03
* -------------------------------------+
* for-in loop iterates throgh an object - 
* which has non-enumerable properties
* -------------------------------------+
**/


class Icon{
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
}
let icon = new Icon(128, 32);


// --- Attach a property via prototype
Icon.prototype.myProp1 = 10;


// ---- Attaching a property but explicitly saying it is not enumerable 
Object.defineProperty(icon, "myProp2", {
	enumerable: false
})
// ---- This will not output "myProp2"
for(let prop in icon) {
	console.log(prop);
}

对于……循环 (for of… loop)

This is a newly introduced feature with ES6. for-of creates a loop on iterable objects. String, Array, TypedArray, Map and Set can be taken as built-in iterable objects.

这是ES6的新功能for-of在可迭代对象上创建一个循环。 StringArrayTypedArrayMapSet可以视为内置的可迭代对象。

See following demo with built-in iterables..

请参阅以下带有内置可迭代对象的演示。

/**
* Example - 01
* -------------------------------------+
* for-of loop with several built-in iterables
* -------------------------------------+
**/


// -- Looping through charactors of a string


for(let i of "String")
	console.log(i)
  
// --- Looping through key-value paris of a Map  
  
let m = new Map();
m.set("a", 1).set("b", 2);


for(let [i, j] of m)
	console.log(`${i}->${j}`);
  
// --- Looping through elements of an array of arrays


for(let [i, j, k] of [[4,5,6], [1,2,3]])
	console.log(i, j, k);

If there is a special requirement custom iterable objects can be defined too. Iterables are just objects but with a special method called Symbol.interator which is known as the default iterator in the iterable protocol concept. Once for-of is executed it calls this default iterator in order to get the iterator object for going through each data element.

如果有特殊要求,也可以定义自定义可迭代对象。 可迭代对象只是对象,但具有一种称为Symbol.interator的特殊方法,该方法在可迭代协议概念中被称为默认迭代器。 一旦执行了for-of ,它将调用此默认迭代器,以获取用于遍历每个数据元素的迭代器对象。

The iterator object has next() method which will provide required data and the stopping condition for the for-of loop. Moreover, this special method and data structure are defined in the iterator protocol. I did an experiment on the console as shown below to simulate what will happen with this looping mechanism.

迭代器对象具有next()方法,它将为for-of循环提供所需的数据和停止条件。 此外,在迭代器协议中定义了这种特殊的方法和数据结构 我在控制台上做了如下所示的实验,以模拟这种循环机制会发生什么。

Image for post
for-of works with the iterator protocol for-of如何与迭代器协议一起工作的实验

As you can see next() method returns each data element details of the array and eventually returns value as undefined also with done: true indicating the iteration has been completed.

如您所见, next()方法返回数组的每个数据元素详细信息,并最终还通过done: true返回未定义的done: true表示迭代已完成。

哪一个? 什么时候? (Which one? and When?)

Each type of for loop is useful in different cases…

每种类型的for循环在不同情况下都很有用……

  • If counters/indexes are needed while accessing an array or indexes related logical stuff are there it is better to go ahead with for loop.

    如果在访问数组时需要计数器/索引或与索引相关的逻辑内容,最好进行for循环。

  • If there is a need to access properties/keys regardless of the order for-in will help.

    如果有必要访问属性/键不管换将有助于秩序。

  • If you just need to iterate through data items of an iterable(also if you need to apply some changes maybe) for-of is an obvious choice.

    如果只需要迭代一个可迭代的数据项(也可能需要应用一些更改), for-of是一个显而易见的选择。

Personally, I would like to choose for-of most of the time.. and for was selected for some algorithmic things.

就个人而言,我希望大多数情况下选择…,并且为某些算法选择了。

Happy coding 😎

快乐编码😎

翻译自: https://medium.com/swlh/javascripts-for-vs-for-in-vs-for-of-in-depth-a589feb88bdd

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值