當使用 forEach 呼叫方法時,物件陣列不執行“if”,但是當我將 if 移動到 forEach 內部時,它可以作業,我試圖弄清楚為什么在運行 forEach 時不觸發物件內部的 if。
有一個默認值 (false) 的 var (responseFlag),因此如果您需要更改 html 渲染,只需在單擊按鈕時更改它 (true/false)。
var responseFlag = 'false',
targetRender = document.getElementById('targethtml'),
templateTrue = '<h2>true</h2>',
templateFalse = '<h2>false</h2>';
//
objDef = {
"objDefs" : [
{
"UIhtml": responseFlag == 'true' ? templateTrue : templateFalse // does not works
// "UIhtml": responseFlag // this works
}
]
};
//
UI_exc = {
outputResult: function() {
objDef.objDefs.forEach(function(key, value){
targetRender.innerHTML =
// responseFlag == 'true' ? templateTrue : templateFalse // this works
key.UIhtml // does not works
console.log(responseFlag)
});
},
clickAction: function() {
document.getElementById('goRender').addEventListener("click", function(){
responseFlag = 'true' // render html base true/false
console.log(responseFlag);
UI_exc.outputResult()
});
}
};
UI_exc.clickAction();
<button id="goRender">Click</button>
<div id="targethtml">[ N ]</div>
uj5u.com熱心網友回復:
我猜的問題是物件已初始化并在那里分配了 UIhtml 屬性,我認為您應該更改UIhtml為一個函式然后呼叫它:
... = key.UIhtml()
console.log(responseFlag)
uj5u.com熱心網友回復:
創建物件文字時,宣告的屬性不是字串,而只是對某些值的參考,例如字串、數字、布林值、物件...
將“UIhtml”更改為 UIhtml。
閱讀此檔案了解更多資訊:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365847.html
標籤:javascript 数组 foreach
上一篇:如何將MultiIndex轉換和重塑為3DNumpy陣列?
下一篇:RUBY:使用結構陣列
