Javascript 为什么在词汇范围中会出现这种不匹配?

Javascript 为什么在词汇范围中会出现这种不匹配?,javascript,node.js,debugging,lexical-scope,Javascript,Node.js,Debugging,Lexical Scope,这个问题在节点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');

这个问题在节点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);

有人能解释为什么会发生这种情况以及如何解决它吗?

我发现了这个问题。在
getLocals()
中,我正在执行

const modifiedTabs = config.tabs.map(tab => {
  return Object.assign(tab, {active: tab.name === name});
});
Object.assign(tab,…)
每次调用时都会覆盖现有的
tab
对象,只为每个选项卡保留最后的分配。因此,所有视图都将数组中的最后一个选项卡显示为活动,因为它们的所有
active
属性都已被最后一个选项卡配置的属性覆盖

解决方案是将参数切换到
Object.assign()
,以便创建而不是覆盖返回的对象:

return Object.assign({active: tab.name === name}, tab);

在您注释掉的行中注销
locals
getLocals(name)
。我猜它们会有所不同,因为你在某个地方变异了一个对象,却没有意识到它。我刚刚找到了变异:
object.assign(tab,{active:tab.name==name})
第11行。。。