我有以下代碼設定顏色變數,然后基于該變數構造表資料背景顏色。沒問題..但是..當我嘗試重新分配另一個顏色值時,相同的變數它沒有生效。使用 conole.log 選項,我可以看到條件值被正確檢測為“OFF”,但我不明白為什么變數不采用“red”的值
let themeOptions = {
color_variable: '#00FF00'
}
get(child(dbref, "Sensor"))
.then((snapshot) => {
snapshot.forEach((child) => {
let table = document.querySelector('table');
if (child.val().Status == "OFF") {
console.log(child.val().Status); // it prints the value "OFF"
let themeOptions = {
color_variable: 'red'
}
}
let template = `
<tr>
<td bgcolor="${themeOptions.color_variable}">${"pump" child.val().PumpID}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().StartTime}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Duration}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().GalsPumped}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Cycle}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Status}</td>
</tr>`;
table.innerHTML = template;
})
});
uj5u.com熱心網友回復:
當你用letor宣告一個變數時const,它的作用域是最近的封閉塊。這意味著當您分配到塊之外時,您的重新分配themeOptions不在范圍內。templateif
如果要重新定義全域變數,請洗掉let宣告。但只分配給特定屬性可能更合適。
if (child.val().Status == "OFF") {
console.log(child.val().Status); // it prints the value "OFF"
themeOptions.color_variable = "red";
}
uj5u.com熱心網友回復:
無法重新定義已宣告的變數
// Wrong
let themeOptions = {
color_variable: '#00FF00'
}
let themeOptions = {
color_variable: 'red'
}
相反,只需修改要更新的屬性:
/* Correct */
let themeOptions = {
color_variable: '#00FF00'
}
themeOptions.color_variable = 'red';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508889.html
上一篇:使用JavaScriptFetchAPI將檔案上傳到FastAPI后端時出現422無法處理的物體錯誤
下一篇:比較兩個陣列物件并洗掉值
