Compare for, for..in, for...of, forEach

Keywords: Javascript Front-end

1 for... in

1.1 enumerable objects

const person = {
  name: 'Lydia',
  age: 21,
};
for (const item in person) {
  console.log(item);
}

The output result is: name age
This result can be simply understood as that for the object, using the for... in... Loop is to loop the key value of the object.

But using for... of... Results are different

const person = {
  name: 'Lydia',
  age: 21,
};
for (const item of person) {
    console.log(item);
  }

Output result TypeError: person is not iterable
This result shows that for... of... Cannot loop objects

What about forEach?

const person = {
  name: 'Lydia',
  age: 21,
}
person.forEach((i) => {
  console.log(i)
})

Output result TypeError: person.forEach is not a function
This result shows that forEach cannot traverse the object

1.2 enumerable array

 const arr = ['a','b','c']
  for (const item in arr) {
    console.log(item);
    console.log(arr[item]);
  }

The output result is 0 'a' 1 'b' 2 'c'
This result shows that using for... in... Is to output the index value, and the array data can be obtained through the index value

But using for... of... Results are different

 const arr = ['a','b','c']
 for (const item of arr) {
    console.log(item);
  }

The output result is' a ',' b ',' c '
This result shows that using for... of... Is the output array value

1.3 prototype object of enumerable array

Array.prototype.sayHello = function(){
  console.log("Hello")
}
Array.prototype.str = 'world';
var myArray = [1,2,3];
myArray.name='array';
for(let index in myArray){
  console.log(index);
}

The output result is: 0 1 2 name sayHello str
This result shows that for in not only returns the subscript of the array, but also returns the prototype object of the array and the attribute value of the array object itself. However, there is also a problem. In the actual work development, these objects may not be needed, and listing them all may cause new problems.

To solve the problem of prototype objects, you can use hasOwnProperty

Array.prototype.sayHello = function(){
  console.log("Hello")
}
Array.prototype.str = 'world';
var myArray = [1,2,3];
myArray.name='array';

for(let index in myArray){
  if(myArray.hasOwnProperty(index)) {
    console.log(index);
  }
}

The output is 0 1 2 name
However, it can be seen from this result that although hasOwnProperty is used, the properties of the array itself will be output

2. Role of foreach

2.1 traversable array

Array.prototype.sayHello = function(){
  console.log("Hello")
}
Array.prototype.str = 'world';
var myArray = ['a','b','c'];
myArray.name='array';

myArray.forEach((value,i) => {
  console.log(value)
  console.log(i)
})

The output is' a '0' b '1' c '2
Using forEach, you can output index values and array values without outputting the prototype object of the array.

2.2 failure to break

One problem with forEach is that execution cannot be interrupted

var arr = [3, 5, 7];
arr.forEach(function (value) {
  console.log(value);
  if (value === 5) {
    return false;
  }
});

The output is 3 5 7
It can be seen from the results that return false is not executed, and it will run to the end

for in also has this problem:

var arr = [3, 5, 7];
for (let value in arr) {
  console.log(arr[value]);
  if (value == 5) {
    break;
  }
}

The output is 3 5 7
It can be seen from the results that break is not executed, and it will run to the end

3 for... of

3.1 traversable array

Array.prototype.sayHello = function(){
  console.log("Hello")
}
Array.prototype.str = 'world';
var myArray = ['a','b','c'];
myArray.name='array';
for(let index of myArray) {
  console.log(index)
}

The output is a b c
Using for of cannot output the index value, but it will not output the prototype object of the array.

3.2 interruptible

var arr = [3, 5, 7];
for (let value of arr) {
  console.log(value);
  if (value == 5) {
    break;
  }
}

The output is 3 5
As a result, break is executed and the loop can be interrupted

3.3 iteratable string

let str = 'hello';
for (let value of str) {
  console.log(value);
}

The output result is' h ',' e ',' l ',' l ',' o '

3.4 iteratable arguments class array object

(function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);

The output is 1 2 3

3.5 iteratable map and set

let mapData = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of mapData) {
  console.log(value);
}
let setData = new Set([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of setData) {
  console.log(value);
}

The output results are 1, 2, 3

4 Summary

for in is suitable for traversal of pure objects, and can only output enumerable properties
forEach is suitable for array traversal that needs to know the index value, but it cannot be interrupted
For of is suitable for array traversal without knowing the index value, because it can be interrupted. In addition, for of is more applicable to the iteration of other strings, class arrays and type arrays

Posted by ksukat on Fri, 12 Nov 2021 11:08:39 -0800