for (let index = 0; index < theArray.length; ++index) {const element = theArray[index];// ...use `element`...}
(很少)for-in有保障-async友好
for (const propertyName in theArray) {if (/*...is an array element property (see below)...*/) {const element = theArray[propertyName];// ...use `element`...}}
function delay(ms) {return new Promise(resolve => {setTimeout(resolve, ms);});}
async function showSlowly(messages) {for (const message of messages) {await delay(400);console.log(message);}}
showSlowly(["So", "long", "and", "thanks", "for", "all", "the", "fish!"]);// `.catch` omitted because we know it never rejects
// (The `NodeList` from `querySelectorAll` is array-like)const divs = document.querySelectorAll("div");for (let index = 0; index < divs.length; ++index) {divs[index].addEventListener('click', e => {console.log("Index is: " + index);});}
function delay(ms) {return new Promise(resolve => {setTimeout(resolve, ms);});}
async function showSlowly(messages) {for (let i = 0; i < messages.length; ++i) {const message = messages[i];await delay(400);console.log(message);}}
showSlowly(["So", "long", "and", "thanks", "for", "all", "the", "fish!"]);// `.catch` omitted because we know it never rejects
// `a` is a sparse arrayconst a = [];a[0] = "a";a[10] = "b";a[10000] = "c";for (const name in a) {if (Object.hasOwn(a, name) && // These checks are/^0$|^[1-9]\d*$/.test(name) && // explainedname <= 4294967294 // below) {const element = a[name];console.log(a[name]);}}
// Utility function for antiquated environments without `forEach`const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);const rexNum = /^0$|^[1-9]\d*$/;function sparseEach(array, callback, thisArg) {for (const name in array) {const index = +name;if (hasOwn(a, name) &&rexNum.test(name) &&index <= 4294967294) {callback.call(thisArg, array[name], index, array);}}}
const a = [];a[5] = "five";a[10] = "ten";a[100000] = "one hundred thousand";a.b = "bee";
sparseEach(a, (value, index) => {console.log("Value at " + index + " is " + value);});
与for一样,如果需要串联完成异步函数中的工作,则for-in在异步函数中运行良好。
function delay(ms) {return new Promise(resolve => {setTimeout(resolve, ms);});}
async function showSlowly(messages) {for (const name in messages) {if (messages.hasOwnProperty(name)) { // Almost always this is the only check people doconst message = messages[name];await delay(400);console.log(message);}}}
showSlowly(["So", "long", "and", "thanks", "for", "all", "the", "fish!"]);// `.catch` omitted because we know it never rejects
5.显式使用迭代器(ES2015+)
for-of隐式使用迭代器,为你做所有的短接工作。有时,你可能想使用迭代器明确。它看起来像这样:
const a = ["a", "b", "c"];const it = a.values(); // Or `const it = a[Symbol.iterator]();` if you likelet entry;while (!(entry = it.next()).done) {const element = entry.value;console.log(element);}
function delay(ms) {return new Promise(resolve => {setTimeout(resolve, ms);});}
async function showSlowly(messages) {const it = messages.values()while (!(entry = it.next()).done) {await delay(400);const element = entry.value;console.log(element);}}
showSlowly(["So", "long", "and", "thanks", "for", "all", "the", "fish!"]);// `.catch` omitted because we know it never rejects
Array.prototype.forEach.call(node.childNodes, (child) => {// Do something with `child`});
(注意,你可以在node.childNodes上使用for-of。
如果您要经常这样做,您可能希望将函数引用的副本获取到变量中以供重用,例如:
// (This is all presumably in a module or some scoping function)const forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// Then later...forEach(node.childNodes, (child) => {// Do something with `child`});
// Typical use (with an arrow function):const divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);
// Traditional function (since `Array.from` can be polyfilled):var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {return element.tagName;});
function forEach(list,callback) {var length = list.length;for (var n = 0; n < length; n++) {callback.call(list[n]);}}
var myArray = ['hello','world'];
forEach(myArray,function(){alert(this); // do something});
var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
//item will be each element in the array
//do something
});
将项从一个数组复制到另一个数组的另一种有用方法是
var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);
['C', 'D', 'E'].forEach(function(element, index) {
console.log(element + " is #" + (index+1) + " in the musical scale");
});
// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale
在这种情况下,我们更感兴趣的是使用一些内置特性对数组进行操作。
Map -它使用回调函数的结果创建一个新数组。当需要设置数组元素的格式时,可以使用此方法。
// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
return elem.toUpperCase();
});
// Output: ['BOB', 'JOE', 'JEN']
var languages = ["Java", "JavaScript", "C#", "Python"];
var i, len, text;
for (i = 0, len = languages.length, text = ""; i < len; i++) {
text += languages[i] + "<br>";
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>
while - loop while a condition is through. It seems to be the fastest loop
var text = "";
var i = 0;
while (i < 10) {
text += i + ") something<br>";
i++;
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>
do/while - also loop through a block of code while the condition is true, will run at least one time
var text = ""
var i = 0;
do {
text += i + ") something <br>";
i++;
}
while (i < 10);
document.getElementById("example").innerHTML = text;
<p id="example"></p>
Functional loops - forEach, map, filter, also reduce (they loop through the function, but they are used if you need to do something with your array, etc.
// For example, in this case we loop through the number and double them up using the map function
var numbers = [65, 44, 12, 4];
document.getElementById("example").innerHTML = numbers.map(function(num){return num * 2});
[].forEach.call(arrayName,function(value,index){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
$("#ul>li").each(function(**index, value**){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
let arr = [1, 2, 3, 4, 5];
arr.forEach((element, index, array) => {
console.log(element * 2);
if (index === 4) {
console.log(array)
}
// index, and oldArray are provided as 2nd and 3th argument by the callback
})
console.log(arr);
let arrSimple = ['a', 'b', 'c'];
for (let letter of arrSimple) {
console.log(letter);
}
示例2: 将单词拆分为字符
let arrFruits = ['apple', 'orange', 'banana'];
for (let [firstLetter, ...restOfTheWord] of arrFruits) {
// Create a shallow copy using the spread operator
let [lastLetter] = [...restOfTheWord].reverse();
console.log(firstLetter, lastLetter, restOfTheWord);
}
示例3: 使用 key和 value进行循环
// let arrSimple = ['a', 'b', 'c'];
// Instead of keeping an index in `i` as per example `for(let i = 0 ; i<arrSimple.length;i++)`
// this example will use a multi-dimensional array of the following format type:
// `arrWithIndex: [number, string][]`
let arrWithIndex = [
[0, 'a'],
[1, 'b'],
[2, 'c'],
];
// Same thing can be achieved using `.map` method
// let arrWithIndex = arrSimple.map((i, idx) => [idx, i]);
// Same thing can be achieved using `Object.entries`
// NOTE: `Object.entries` method doesn't work on Internet Explorer unless it's polyfilled
// let arrWithIndex = Object.entries(arrSimple);
for (let [key, value] of arrWithIndex) {
console.log(key, value);
}
示例4: 内联获取对象属性
let arrWithObjects = [{
name: 'Jon',
age: 32
},
{
name: 'Elise',
age: 33
}
];
for (let { name, age: aliasForAge } of arrWithObjects) {
console.log(name, aliasForAge);
}
let arrWithIndex = [
[0, 'a'],
[1, 'b'],
[2, 'c'],
];
// Not to be confused here, `forEachIndex` is the real index
// `mappedIndex` was created by "another user", so you can't really trust it
arrWithIndex.forEach(([mappedIndex, item], forEachIndex) => {
console.log(forEachIndex, mappedIndex, item);
});
例7: 与 .forEach一起使用 例子4
let arrWithObjects = [{
name: 'Jon',
age: 32
},
{
name: 'Elise',
age: 33
}
];
// NOTE: Destructuring objects while using shorthand functions
// are required to be surrounded by parentheses
arrWithObjects.forEach( ({ name, age: aliasForAge }) => {
console.log(name, aliasForAge)
});
// Looping through arrays using the foreach ECMAScript 6 way
var data = new Array(1, 2, 3, 4, 5);
data.forEach((val,index) => {
console.log("index: ", index); // Index
console.log("value: ", val); // Value
});
/* Get all forms */
document.querySelectorAll( "form" ).forEach( form => {
/* For each form, add the onsubmit event */
form.addEventListener( "submit", event => {
event.preventDefault(); // Return false
/* Display it */
alert(event.target.action);
console.log(event.target);
} );
} );