Home  >  Article  >  Web Front-end  >  What are the similar for loops in es6?

What are the similar for loops in es6?

青灯夜游
青灯夜游Original
2022-10-17 17:26:531088browse

There are similar for loops in es6: 1. "for-in" loop, the objects it traverses are not limited to arrays, but can also traverse objects. The syntax is "for (key name in object) {.. .}"; 2. forEach loop, execute the callback function once for each item in the array that contains a valid value, the syntax is "array.forEach(callback function, thisValue)"; 3. "for-of" loop, the syntax is "for( Current value of array){...}".

What are the similar for loops in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

ECMAScript6 (ES6 for short) supports 4 types of for loops.

  • Simple for loop

  • for-in

  • forEach

  • for-of

Let’s take a look at these four types of for loops.

Simple for loop

Let’s take a look at the most common way of writing:

const arr = [1, 2, 3];
for(let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

What are the similar for loops in es6?

## When the array length will not change during the loop, we should store the array length in a variable, which will achieve better efficiency. The following is an improved way of writing:

const arr = [1, 2, 3];
for(let i = 0, len = arr.length; i < len; i++) {
    console.log(arr[i]);
}

What are the similar for loops in es6?

for-in

Normally, we can use for-in to traverse the contents of the array. The code is as follows:

const arr = [1, 2, 3];
let index;
for(index in arr) {
    console.log("arr[" + index + "] = " + arr[index]);
}

Under normal circumstances, the running result As follows:


What are the similar for loops in es6?

#But this often causes problems.

The truth about for-in

for-in loop traverses the properties of the object, not the index of the array. Therefore, the objects traversed by for-in are not limited to arrays, but can also traverse objects. An example is as follows:

const person = {
    fname: "san",
    lname: "zhang",
    age: 99
};
let info;
for(info in person) {
    console.log("person[" + info + "] = " + person[info]);
}

The result is as follows:

2-What are the similar for loops in es6?

It should be noted that the order in which for-in traverses the attributes is not determined, that is, the order of the output results is the same as The order of the properties in the object does not matter, nor does it matter the alphabetical order of the properties, nor does it matter any other order.

The truth about Array

Array is an object in Javascript, and the index of Array is the property name. In fact, "array" in Javascript is somewhat misleading. Array in Javascript is not like arrays in most other languages. First of all, Array in Javascript is not continuous in memory. Secondly, the index of Array does not refer to the offset. In fact, the index of Array is not of Number type, but of String type. The reason why we can use arr[0] correctly is that the language can automatically convert 0 of Number type into "0" of String type. Therefore, there are never Array indexes in Javascript, but only properties like "0", "1", etc. Interestingly, every Array object has a length property, causing it to behave more like arrays in other languages. But why is the length attribute not output when traversing the Array object? That's because for-in can only iterate over "enumerable properties", length is a non-enumerable property, and in fact, Array objects have many other non-enumerable properties.

Now, let’s go back and look at the example of using for-in to loop an array. Let’s modify the previous example of traversing the array:

const arr = [1, 2, 3];
arr.name = "Hello world";
let index;
for(index in arr) {
    console.log("arr[" + index + "] = " + arr[index]);
}

The running result is:


What are the similar for loops in es6?

We see that for-in loops through our new "name" attribute, because for-in traverses all attributes of the object, not just the "index". At the same time, it should be noted that the index values ​​output here, that is, "0", "1", and "2" are not of Number type, but of String type, because they are output as attributes, not indexes. Does that mean that we can just output the contents of the array without adding new properties to our Array object? the answer is negative. Because for-in not only traverses the properties of the array itself, it also traverses all enumerable properties on the array prototype chain. Let's look at an example below:


Array.prototype.fatherName = "Father";
const arr = [1, 2, 3];
arr.name = "Hello world";
let index;
for(index in arr) {
    console.log("arr[" + index + "] = " + arr[index]);
}

The running result is:


arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[name] = Hello world
arr[fatherName] = Father

Writing this, we can find that for-in is not suitable for traversing elements in Array , which is more suitable for traversing properties in objects, which is also the original intention of its creation. There is one exception, that is, sparse arrays. Consider the following example:


let key;
const arr = [];
arr[0] = "a";
arr[100] = "b";
arr[10000] = "c";
for(key in arr) {
    if(arr.hasOwnProperty(key)  &&   
        /^0$|^[1-9]\d*$/.test(key) &&   
        key <= 4294967294              
        ) {
        console.log(arr[key]);
    }
}

for-in 只会遍历存在的实体,上面的例子中, for-in 遍历了3次(遍历属性分别为”0″、 “100″、 “10000″的元素,普通 for 循环则会遍历 10001 次)。所以,只要处理得当, for-in 在遍历 Array 中元素也能发挥巨大作用。

为了避免重复劳动,我们可以包装一下上面的代码:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) &&
        /^0$|^[1-9]\d*$/.test(prop) &&
        prop <= 4294967294; // 2^32 - 2
}

使用示例如下:

for (let key in arr) {
    if (arrayHasOwnIndex(arr, key)) {
        console.log(arr[key]);
    }
}

for-in 性能

正如上面所说,每次迭代操作会同时搜索实例或者原型属性, for-in 循环的每次迭代都会产生更多开销,因此要比其他循环类型慢,一般速度为其他类型循环的 1/7。因此,除非明确需要迭代一个属性数量未知的对象,否则应避免使用 for-in 循环。如果需要遍历一个数量有限的已知属性列表,使用其他循环会更快,比如下面的例子:

const obj = {
    "prop1": "value1",
    "prop2": "value2"
};
 
const props = ["prop1", "prop2"];
for(let i = 0; i < props.length; i++) {
    console.log(obj[props[i]]);
}

上面代码中,将对象的属性都存入一个数组中,相对于 for-in 查找每一个属性,该代码只关注给定的属性,节省了循环的开销和时间。

forEach

在 ES5 中,引入了新的循环,即 forEach 循环。

const arr = [1, 2, 3];
arr.forEach((data) => {
    console.log(data);
});

运行结果:

1
2
3

forEach 方法为数组中含有有效值的每一项执行一次 callback 函数,那些已删除(使用 delete 方法等情况)或者从未赋值的项将被跳过(不包括那些值为 undefined 或 null 的项)。 callback 函数会被依次传入三个参数:

  • 数组当前项的值;
  • 数组当前项的索引;
  • 数组对象本身;

需要注意的是,forEach 遍历的范围在第一次调用 callback 前就会确定。调用forEach 后添加到数组中的项不会被 callback 访问到。如果已经存在的值被改变,则传递给 callback 的值是 forEach 遍历到他们那一刻的值。已删除的项不会被遍历到。

const arr = [];
arr[0] = "a";
arr[3] = "b";
arr[10] = "c";
arr.name = "Hello world";
arr.forEach((data, index, array) => {
    console.log(data, index, array);
});

运行结果:

a 0 ["a", 3: "b", 10: "c", name: "Hello world"]
b 3 ["a", 3: "b", 10: "c", name: "Hello world"]
c 10 ["a", 3: "b", 10: "c", name: "Hello world"]

这里的 index 是 Number 类型,并且也不会像 for-in 一样遍历原型链上的属性。

所以,使用 forEach 时,我们不需要专门地声明 index 和遍历的元素,因为这些都作为回调函数的参数。

另外,forEach 将会遍历数组中的所有元素,但是 ES5 定义了一些其他有用的方法,下面是一部分:

  • every: 循环在第一次 return false 后返回
  • some: 循环在第一次 return true 后返回
  • filter: 返回一个新的数组,该数组内的元素满足回调函数
  • map: 将原数组中的元素处理后再返回
  • reduce: 对数组中的元素依次处理,将上次处理结果作为下次处理的输入,最后得到最终结果。

forEach 性能

大家可以看 jsPerf ,在不同浏览器下测试的结果都是 forEach 的速度不如 for。如果大家把测试代码放在控制台的话,可能会得到不一样的结果,主要原因是控制台的执行环境与真实的代码执行环境有所区别。

for-of

先来看个例子:

const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];
for(let data of arr) {
    console.log(data);
}

运行结果是:

a
b
c

为什么要引进 for-of?

要回答这个问题,我们先来看看ES6之前的 3 种 for 循环有什么缺陷:

  • forEach 不能 break 和 return;
  • for-in 缺点更加明显,它不仅遍历数组中的元素,还会遍历自定义的属性,甚至原型链上的属性都被访问到。而且,遍历数组元素的顺序可能是随机的。

所以,鉴于以上种种缺陷,我们需要改进原先的 for 循环。但 ES6 不会破坏你已经写好的 JS 代码。目前,成千上万的 Web 网站依赖 for-in 循环,其中一些网站甚至将其用于数组遍历。如果想通过修正 for-in 循环增加数组遍历支持会让这一切变得更加混乱,因此,标准委员会在 ES6 中增加了一种新的循环语法来解决目前的问题,即 for-of 。

那 for-of 到底可以干什么呢?

  • 跟 forEach 相比,可以正确响应 break, continue, return。
  • for-of 循环不仅支持数组,还支持大多数类数组对象,例如 DOM nodelist 对象。
  • for-of 循环也支持字符串遍历,它将字符串视为一系列 Unicode 字符来进行遍历。
  • for-of 也支持 Map 和 Set (两者均为 ES6 中新增的类型)对象遍历。

总结一下,for-of 循环有以下几个特征:

  • 这是最简洁、最直接的遍历数组元素的语法。
  • 这个方法避开了 for-in 循环的所有缺陷。
  • 与 forEach 不同的是,它可以正确响应 break、continue 和 return 语句。
  • 其不仅可以遍历数组,还可以遍历类数组对象和其他可迭代对象。

但需要注意的是,for-of循环不支持普通对象,但如果你想迭代一个对象的属性,你可以用
for-in 循环(这也是它的本职工作)。

最后要说的是,ES6 引进的另一个方式也能实现遍历数组的值,那就是 Iterator。上个例子:

const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];
const iter = arr[Symbol.iterator]();
 
iter.next() // { value: &#39;a&#39;, done: false }
iter.next() // { value: &#39;b&#39;, done: false }
iter.next() // { value: &#39;c&#39;, done: false }
iter.next() // { value: undefined, done: true }

前面的不多说,重点描述for-of

for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象

for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:

window.onload=function(){ 
   const arr = [55,00, 11, 22];
   arr.name = "hello";
  // Array.prototype.FatherName = &#39;FatherName&#39;;
   /*for(let key in arr){
    console.log(&#39;key=&#39;+key+&#39;,key.value=&#39;+arr[key]);
   }*/
   /* arr.forEach((data) => {console.log(data);});*/
  /* arr.forEach((data,index,arr) => {console.log(data+&#39;,&#39;+index+&#39;,&#39;+arr);});*/
  /*for(let key of arr){
    console.log(key);
  }*/
  var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  const stringArr = [string1,string2];
  for(let key of stringArr){
    console.log(key);
  }
  for(let key of string1){
    console.log(key);
  }
}

结果:

What are the similar for loops in es6?

现在,只需记住:

  • 这是最简洁、最直接的遍历数组元素的语法
  • 这个方法避开了for-in循环的所有缺陷
  • 与forEach()不同的是,它可以正确响应break、continue和return语句

for-in循环用来遍历对象属性。

for-of循环用来遍历数据—例如数组中的值。

它同样支持Map和Set对象遍历。

Map和Set对象是ES6中新增的类型。ES6中的Map和Set和java中并无太大出入。

SetMap类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set中,没有重复的key。

要创建一个Set,需要提供一个Array作为输入,或者直接创建一个空Set

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3

What are the similar for loops in es6?

重复元素在Set中自动被过滤:

var s = new Set([1, 2, 3, 3, '3']);
console.log(s); // Set {1, 2, 3, "3"}

What are the similar for loops in es6?

通过add(key)方法可以添加元素到Set中,可以重复添加,但不会有效果:

var s = new Set([1, 2, 3]);
s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Set {1, 2, 3, 4}

通过delete(key)方法可以删除元素:

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}

Set对象可以自动排除重复项

var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  var string3 = &#39;opqrstuvwxyc&#39;;
  var string4 = &#39;opqrstuvwxyz&#39;;
 
  const stringArr = [string1,string2,string3,string4];
 
 
 var newSet = new Set(stringArr);
  for(let key of newSet){
    console.log(key);
  }

结果:

What are the similar for loops in es6?

Map对象稍有不同:内含的数据由键值对组成,所以你需要使用解构(destructuring)来将键值对拆解为两个独立的变量:

for (var [key, value] of phoneBookMap) {   
console.log(key + "&#39;s phone number is: " + value);
}

 示例

var m = new Map([[1, &#39;Michael&#39;], [2, &#39;Bob&#39;], [3, &#39;Tracy&#39;]]);
  var map = new Map([[&#39;1&#39;,&#39;Jckey&#39;],[&#39;2&#39;,&#39;Mike&#39;],[&#39;3&#39;,&#39;zhengxin&#39;]]);
  map.set(&#39;4&#39;,&#39;Adam&#39;);//添加key-value
  map.set(&#39;5&#39;,&#39;Tom&#39;);
  map.set(&#39;6&#39;,&#39;Jerry&#39;);
  console.log(map.get(&#39;6&#39;));
  map.delete(&#39;6&#39;);
   console.log(map.get(&#39;6&#39;));
  for(var [key,value] of map) {
    console.log(&#39;key=&#39;+key+&#39; , value=&#39;+value);
  }

结果:

What are the similar for loops in es6?

【相关推荐:javascript视频教程编程视频

The above is the detailed content of What are the similar for loops in es6?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn