最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么JS将['foo']解释为读取属性而不是数组声明

运维笔记admin12浏览0评论

为什么JS将['foo']解释为读取属性而不是数组声明

为什么JS将['foo']解释为读取属性而不是数组声明

Mocha Github问题跟踪器上的这个问题很有趣

此代码按预期工作:

describe('before/after with data-driven tests', () => {
  before(() => console.log('before worked'));
  beforeEach(() => console.log('beforeEach worked'));
  afterEach(() => console.log('afterEach worked'));
  after(() => console.log('after worked'));

  ['foo'].forEach((item) => {
    it(`works for item ${item}`, () => {
      console.log('item is', item)
    })
  })
})

但是这段代码很奇怪:

describe('before/after with data-driven tests', () => {
  before(() => console.log('before worked'))
  beforeEach(() => console.log('beforeEach worked'))
  afterEach(() => console.log('afterEach worked'))
  after(() => console.log('after worked'))
  [ 'foo' ].forEach((item) => {
    it(`works for item ${item}`, () => {
      console.log('item is', item)
    })
  })
})

如果用mocha执行第二个示例代码,它会尝试从未定义的变量中读取'foo'。有谁知道为什么?这是错误跟踪:

    [ 'foo' ].forEach((item) => {
    ^

TypeError: Cannot read property 'foo' of undefined

很奇怪!但我相信有一个很好的解释。

回答如下:

原因是第二个例子中缺少;

after(() => console.log('after worked'))
  [ 'foo' ].forEach((item) => {
    it(`works for item ${item}`, () => {
      console.log('item is', item)
    })
  })

如果没有分号,则表示“调用函数after”并从返回的结果中选择此键。但是在返回undefined之后,你就得到了错误。

发布评论

评论列表(0)

  1. 暂无评论