代碼的結果是:
test0: apple
1: orange
2: cherry
我想知道為什么我的文本變數在第二個和第三個回圈中等于“”,我希望將先前的值添加到文本變數的初始值中,誰能解釋一下文本變數會發生什么以及邏輯是什么在這個例子中的 forEach ?
let text = "test";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
document.getElementById("demo").innerHTML = text;
function myFunction(item, index) {
text = index ": " item "<br>";
}
<p id="demo"></p>
uj5u.com熱心網友回復:
您的回圈運行時文本test僅添加一次。在開始和之后更新變數text。
如果您想在每次迭代中添加,只需將其保存在一個單獨的變數中并繼續添加。
let text = "";
let test = "test";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
document.getElementById("demo").innerHTML = text;
function myFunction(item, index) {
text = text test index ": " item "<br>";
}
<p id="demo"></p>
uj5u.com熱心網友回復:
您的代碼按預期作業。使用 innerText 而不是 innerHTML 可能會說明情況
let text = "test";
const fruits = ["apple", "orange", "cherry"];
//fruits.forEach(myFunction);
document.getElementById("demo").innerText = text;
function myFunction(item, index) {
text = index ": " item "<br>";
document.getElementById("demo").innerText = text;
console.log(item,index);
}
window.setTimeout( myFunction.bind(null,fruits.shift(),0), 1000);
window.setTimeout( myFunction.bind(null,fruits.shift(),1), 2000);
window.setTimeout( myFunction.bind(null,fruits.shift(),2), 3000);
<p id="demo"></p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/343429.html
標籤:javascript 变量 foreach 逻辑 让
上一篇:如何在React中動態命名變數
