在前端开发过程中,我们经常使用到JavaScript 提供了很多种循环和迭代的方法,常见for, for…of, for…in, while, Array.forEach, 以及 Array.* (还有一些 Arra...
constbeforeDiv=document.getElementById('loopResultsBefore');constafterDiv=document.getElementById('loopResultsAfter');constobj={"a":"JavaScript",1:"PHP","b":"Python",2:"Java"};for(letkeyinobj){beforeDiv.innerHTML+=key+": "+obj[key]+"";if(!isNaN(key)){obj[key-1]=obj[key];}}f...
leti=0;letstart=Date.now();functioncount(){// 做一个繁重的任务for(letj=0;j<1e9;j++){i++;}alert("Done in "+(Date.now()-start)+'ms');}count(); 浏览器甚至可能会显示一个“脚本执行时间过长”的警告。 让我们使用嵌套的setTimeout调用来拆分这个任务: 代码语言:javascript 代码运行次数:0...
for (let prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); } 这段代码会遍历对象obj的每一个属性,并打印属性名和对应的值。 FOR…OF循环 for…of _loop_是一个相对较新的迭代语法,用于遍历可迭代对象(如数组、字符串等)的值。例如: let array = [1, 2, 3, 4, 5]; for (let...
Using let in a loop:Example let i = 5; for (let i = 0; i < 10; i++) { // some code} // Here i is 5 Try it Yourself » In the first example, using var, the variable declared in the loop redeclares the variable outside the loop. ...
letstartTime = performance.now(); for(letkeyinobj){ // console.log(key, obj[key]); } letendTime = performance.now(); console.log((endTime - startTime) +"ms"); } functiondoObjForLoop2(obj){ letstartTime = performance.now(); ...
for(letx of cars) { text += x +" "; } Try it Yourself » Looping over a String Example letlanguage ="JavaScript"; lettext =""; for(letx of language) { text += x +" "; } Try it Yourself » Learn more in the chapter:JavaScript Loop For/In/Of. ...
In JavaScript, the for loop is used for iterating over a block of code a certain number of times, or to iterate over the elements of an array. Here's a quick example of the for loop. You can read the rest of the tutorial for more details. Example for (let i = 0; i < 3; i...
In the next example, we’ll create an empty array and populate it with the loop counter variable. modifyArray.js // Initialize empty arrayletarrayExample=[];// Initialize loop to run 3 timesfor(leti=0;i<3;i++){// Update array with variable valuearrayExample.push(i);console.log(array...
// Normal loop for (let i = 0; i < menu.length; i++) { console.log(menu[i]); } 1. 2. 3. 4. 5. 6. 通过方法(for-of循环)来逐次遍历数组中的每个元素: for(const item of menu){ console.log(item); } 1. 2. 3. 甚至你也可以写成这样: ...