我試圖從另一個檔案中訪問 dataCount 變數,該變數由updateData函式更新,該函式將陣列作為引數,并且當 pop 函式回傳新長度時,我已將其直接傳遞給updateStatus函式。但即使在更新并訪問它之后仍然給我0。
// status.js 檔案
var dataCount = 0;
let data = []
function updateStatus(num, opp){
if (opp == "add"){
dataCount = num
} else if (opp == "sub") {
dataCount -= num
} else {
dataCount = num;
}
}
function updateData(arr){
updateStatus(data.push(arr), 'update');
}
module.exports = {
dataCount: dataCount,
updateStatus: updateStatus,
data: data,
updateData: updateData
}
// 中間件.js 檔案
const status = require('./status');
const methods = require('./helperFunctions')
class Middleware{
constructor(){
}
async populateIfLess(req, res, next){
if (status.dataCount < 4){
try {
// Fetches the data from database and stores in data
const data = await methods.fetchMeaning();
Object.entries(data).map(entry => {
status.updateData([entry[0], entry[1]])
})
methods.log('Data populated on')
setTimeout(() => {
console.log(status.dataCount)
}, 1500);
next()
} catch (error) {
methods.log(error);
res.send({ERROR: "Something went wrong, please check log file."}).end()
}
}
}
}
uj5u.com熱心網友回復:
您正在將 的值dataCount(它是一個數字,所以是一個基元)復制到一個物件的屬性,然后您正在匯出該物件。
稍后您更新其dataCount對物件沒有影響的值,因為數字是原始的(而不是通過參考處理)。
您需要修改module.exports.dataCount。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/520433.html
上一篇:ReactNative:為什么在App()中宣告的變數會不斷重置,而在外部宣告的變數卻沒有?
下一篇:變數初始化后拋出初始化錯誤
