Array is an object in Javascript, and the index of Array is the property name. The output index values, “0”, “1”, and “2”, are not of type Number, but of type String, because they are output as attributes, not indexes.

In ES5, there are three for loops: for, for-in, and forEach

In ECMAScript6 (ES6 for short) released in June 2015, a new type of loop was added: for-of

forEach

var arr = [1.2.3];
arr.forEach((data) = > {
    console.log(data);
});
// The output is as follows
// 1, 2, 3
Copy the code

The forEach method performs a callback forEach item in the array that has a valid value. Items that have been deleted (using the delete method, etc.) or that have never been assigned a value are skipped (excluding those whose value is undefined or null). The callback function is passed three arguments in turn:

  • The value of the current item in the array;
  • The index of the current item in the array;
  • The array object itself;

for-in

JavaScript’s original for… In loop, can only get the key name of the object, not the key value directly.

var obj = { name:'Joe' };
for (var i in obj){
    console.log(i)	// name
}
Copy the code

for-of

What are the drawbacks of the three for loops prior to ES6:

  • forEachCan’tbreakreturn;
  • for-inThe disadvantage is more obvious, it not only iterates through the elements in the array, but also traverses custom attributes, and even attributes on the prototype chain are accessed. Furthermore, the order in which the elements of the traversal array are traversed can be random.

ES6 provided for… The of loop, which allows traversal to obtain key values.

var arr = ['a'.'b'.'c'.'d'];
for (let a in arr) {
  console.log(a); // 0 1 2 3
}

for (let a of arr) {
  console.log(a); // a b c d
}
Copy the code

for… The of loop calls the traverser interface, which returns only properties with numeric indexes.

let arr = [3.5.7];
arr.foo = 'hello';

/** arr=[ 0: 3 1: 5 2: 7 foo: "hello" ] */
for (let i in arr) {
  console.log(i); // "0", "1", "2", "foo"
}

for (let i of arr) {
  console.log(i); //  "3", "5", "7"
}
Copy the code