Javascript全局变量未更新



函数更新dataCount变量后,我正试图从另一个文件访问该变量,该函数将数组作为参数,并作为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
}

//middleware.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()
}
}
}
}

您正在将dataCount的值(这是一个数字,因此是一个基元(复制到对象的属性,然后导出该对象。

稍后将更新dataCount的值,该值对对象没有影响,因为数字是基元(不通过引用处理(。

您需要修改module.exports.dataCount

最新更新