0
此問題出現在節點6.9.4和7.0.0中,我找不到原因。我沒有在其他版本中測試過。請參閱下面的Node.js程序中的評論:爲什麼詞彙範圍的匹配不匹配?
const express = require('express');
const adaro = require('adaro');
const app = express();
const tabs = require('./config/tabs.json');
const config = require('./config/locals.js');
function getLocals(name) {
const modifiedTabs = config.tabs.map(tab => {
return Object.assign(tab, {active: tab.name === name});
});
return Object.assign({tab: name}, config, {tabs: modifiedTabs});
}
app.engine('dust', adaro.dust());
app.set('view engine', 'dust');
app.set('x-powered-by', false);
app.use(express.static('static'));
tabs.map(tab => tab.name).forEach(name => {
const locals = getLocals(name);
const tab = locals.tabs.find(tab => tab.active);
// these are always true
console.log(tab === locals.tabs.find(tab => tab.active));
function callback(req, res) {
// const locals = getLocals(name);
// this should be true, but is false unless the line above is commented in
console.log(tab === locals.tabs.find(tab => tab.active));
res.render('main', locals);
}
if (tab.url !== '/' + tab.id) {
app.get(tab.url, callback);
}
app.get('/' + tab.id, callback);
});
app.all('*', function (req, res) {
res.sendStatus(404);
});
app.listen(process.env.PORT || 8000);
任何人都可以解釋爲什麼發生這種情況,以及如何解決它?
註銷'locals'和'getLocals(名稱)'在該行註釋掉。我的猜測是他們會有所不同,因爲你在某處變異了一個對象而沒有意識到它。 – cdhowie
* facepalm *我剛發現這個變種:'Object.assign(tab,{active:tab.name === name})'line 11 ... –