for 关键字是一种语言结构,这是迭代事物的最快和最“原始”的方式。它有三种样式:
C 风格 for: for ( initializer; condition; iterator ) { code... } - 这是最灵活且经过时间考验的版本。要遍历列表,您需要开始遍历从 0 到列表长度的所有列表索引。你也可以
遍历每隔一个,第三个等元素。大多数时候,这已经足够了。
Javascript for-in for (var key in object) { code ... } - 这是遍历对象中每个键的好方法,例如,输出 JSON 对象的所有值。
(ES2015) Javascript for-of: for (var item of collection) { code ... } - 这是新的,可在现代浏览器中使用。它使您可以跳过索引和计数器,并让您遍历集合的每个项目。 (例如,产品列表中的每个对象。)它与 C 样式的功能相同,但更易于使用。
但是,forEach 函数特定于 Javascript 中的 Array 对象,并允许您为数组中的每个项目运行一个函数。如果您有一个实用功能可以为您完成所有工作,那就太好了。
以下是如何使用上述所有类型的迭代:
// most plain kind of array with a length of 7
var myArray = [1, 2, 3, 4, 5, 6, undefined];
// a weird kind of array with no values between index 3 and 100
// its length is 102
var mySparseArray = [1, 2, 3, 4];
mySparseArray[100] = 5;
mySparseArray[101] = 6;
// 1. C-style for
// ** can control how index is incremented
// ** needs an extra variable to iterate with
for (var i = 0; i < myArray.length; i += 1) {
console.log(myArray[i]);
// logs 1, 2, 3, 4, 5, 6, undefined
}
for (var i = 0; i < mySparseArray.length; i += 1) {
console.log(myArray[i]);
// logs 1, 2, 3, 4, undefined, undefined, ... (up to index 100), 5, 6
}
// 2. for..in
// ** keys are iterated over in non-guaranteed order
// (you might get 2, "length", 1, 0, 3)
// ** all enumerable keys are included, that might include things other than indexes.
for (var key in myArray) {
console.log(myArray[key]);
// logs 1, 2, 3, 4, 5, 6
}
for (var key in mySparseArray) {
console.log(mySparseArray[key]);
// logs 1, 2, 3, 4, 5, 6
// this for-loop "thinks" the array is an object with numbers for keys
}
// 3. for..of
// ** only available in browsers with ES2015 support
// ** supports many other things than Arrays - TypedArrays, Iterators...
for (var item of myArray) {
console.log(item);
}
for (var item of mySparseArray) {
console.log(item);
// logs 1, 2, 3, 4, undefined, undefined, ... (up to index 100), 5, 6
}
// 4. forEach
// ** calls a function for each element (considered slow)
// ** supports only Arrays (unless you call it with Array.prototype.forEach.call)
function myCallback(element) {
console.log(element);
}
myArray.forEach(myCallback); // logs 1, 2, 3, 4, 5, 6
mySparseArray.forEach(myCallback); // logs 1, 2, 3, 4, 5, 6
请务必在浏览器的开发者控制台中尝试这些!您可以看到上述每段代码的运行情况。
请务必查看the MDN reference on iterations.