You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS中为多个变量声明相同值,现有写法报no-undef错误如何解决

问题原因

你使用的是ES6对象属性简写语法,而非多属性同值赋值语法。在对象字面量中单独写today等价于today: today,要求当前作用域必须已经声明过名为today的变量才能正常运行,你未提前声明该变量,因此触发了ESLint的no-undef报错。

正确实现方式

如果你需要给多个对象属性赋相同初始值,可以采用以下写法:

  • 方式1:先声明公共初始值再分别赋值
data () {
  // 注意:Date为引用类型,如下写法两个属性会指向同一个Date实例,修改其中一个会同步影响另一个
  const initDate = new Date()
  return {
    today: initDate,
    tomorrow: initDate
  }
}

如果需要两个独立的Date实例,调整为如下写法即可:

data () {
  return {
    today: new Date(),
    tomorrow: new Date()
  }
}
  • 方式2:先批量初始化变量再用对象简写返回
data () {
  // 批量生成2个独立的Date实例
  const [today, tomorrow] = Array.from({length: 2}, () => new Date())
  // 此处用对象简写,等价于 today: today, tomorrow: tomorrow
  return {
    today,
    tomorrow
  }
}

内容的提问来源于stack exchange,提问作者hayaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:54:05