如題,懇請各位大大解答,謝謝
Question data format[{ id: 0, name: "temp0", option: ["A", "B"] }, { id: 1, name: "temp1", option: ["A", "C"] }]
const mysqlQuery = () => {
return new Promise((resolve) => {
question.map(x => {
mysqldb.query(sql, (err, rows, fields) => {
if (!err) {
x.totalQCount = rows[0].NumberOfQ //add new attribute and value
console.log(x.totalQCount) //display the value
console.log(x) //But not display new attribute and value
resolve(rows)
}
})//end mysql query
})//end for
})
} //end Promise
} //end for
await mysqlQuery();
另外的版本也無法運行
for (let i = 0; i < question.length; i++) {
const mysqlQuery = () => {
return new Promise((resolve) => {
mysqldb.query("select COUNT(UID) AS NumberOfQ FROM AnswerState where QID =?", [question[i]._id.toString()], (err, rows, fields) => {
if (!err) {
// console.log(rows);
// question[i].totalQCount = rows[0].NumberOfQ
temp = rows[0].NumberOfQ
resolve(rows)
} else {
console.log(err);
}
})//end mysql query
})
} //end Promise
await mysqlQuery()
question[i].totalQCount = 123
console.log(question[i].totalQCount)
console.log(question) // 一樣沒有增加新屬性與新值
}//end for
強烈建議你先用callback就好,理清思路。(包含async/await, Promise, const、let、arrow都先不要用,除非你很清楚他在做什麼)
另外,用console.log輸出物件時,先用JSON.stringify把他轉成json字串,不然console.log輸出的不是物件在傳給console.log時當下的狀態。
試試用
question[i][totalQCount] = 123
可是我剛才測試直接 questions[i].totalCount = 100 是有效的
https://jsfiddle.net/p40de3kv/3/
let questions = [{ id: 0, name: "temp0", option: ["A", "B"] },
{ id: 1, name: "temp1", option: ["A", "C"] }];
console.log("Orginal Questions:" , questions)
for (let i = 0; i < questions.length; i++) {
questions[i].totalCount = 100
console.log((i+1) + "'s Question:" , questions[i])
}
/* let i = 1;
questions.map(question => {
question.totalCount = 100;
console.log((i++) + "'s Question:", question)
return question;
}) */
console.log("Adjust Questions:" , questions)
"Orginal Questions:", [{
id: 0,
name: "temp0",
option: ["A", "B"]
}, {
id: 1,
name: "temp1",
option: ["A", "C"]
}]
"1's Question:", {
id: 0,
name: "temp0",
option: ["A", "B"],
totalCount: 100
}
"2's Question:", {
id: 1,
name: "temp1",
option: ["A", "C"],
totalCount: 100
}
"Adjust Questions:", [{
id: 0,
name: "temp0",
option: ["A", "B"],
totalCount: 100
}, {
id: 1,
name: "temp1",
option: ["A", "C"],
totalCount: 100
}]
在MYSQL QUERY之下這個會變無效的, 不過還是謝謝你的回答
你的 console.log(question[i].totalQCount) 出來有值還是undefind ?
你把它改成 console.log(i, question[i].totalQCount),看一下出來的結果是什麼。
question[i].totalQCoun會出來值123
你試試看這兩行出來的結果:
console.log(i, question[i].totalQCount)
console.log(i, question[i])
0 123
0 { id: 0, name: "temp0", option: ["A", "B"] }
是不是出來的json是readonly
下面這個問題跟你的情境很像
你在最上面加上:
'use strict';
看會不會跑出錯誤訊息。
https://stackoverflow.com/questions/58674443/why-cant-i-change-object-property-in-javascript
已解決問題~ 感謝回答