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

JavaScript解构对象location属性提示标识符已声明报错问题求助

问题原因

你遇到的报错是浏览器环境的全局内置变量冲突导致的:

  • 浏览器的全局作用域默认存在内置的window.location属性,用于读写当前页面的URL相关信息,属于全局已经声明的标识符
  • 你在全局作用域下使用const声明同名的location变量,而const规范不允许重复声明同一作用域内已存在的标识符,因此抛出"property has been declared"的错误。其余属性没有和全局内置变量重名,所以可以正常运行。
  • 补充:如果在Node.js环境运行这段代码不会触发报错,因为Node.js全局作用域没有内置location变量。

解决方案

方案1:解构时重命名变量(最推荐)

解构赋值时给location属性设置别名,避免和全局变量冲突:

'use strict';
const restaurant = {
  name: 'Classico Italiano',
  location: 'Via Angelo Tavanti 23, Firence, Italy',
  categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
  starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
  mainMenu: ['Pizza', 'Pasta', 'Risotto'],
  hello_kitty: function (two, three) {
    return [this.starterMenu[two], this.mainMenu[three]];
  },
};

// 解构时将location重命名为restaurantLocation
const { location: restaurantLocation } = restaurant;
console.log(restaurantLocation); // 正常输出餐厅地址

方案2:将代码放入局部作用域执行

把所有代码包裹在块级作用域、函数作用域或立即执行函数中,避免变量泄漏到全局,就不会和全局location冲突:

'use strict';
// 用块级作用域包裹全部代码
{
  const restaurant = {
    name: 'Classico Italiano',
    location: 'Via Angelo Tavanti 23, Firence, Italy',
    categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
    starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
    mainMenu: ['Pizza', 'Pasta', 'Risotto'],
    hello_kitty: function (two, three) {
      return [this.starterMenu[two], this.mainMenu[three]];
    },
  };

  const { location } = restaurant;
  console.log(location); // 正常输出餐厅地址
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:18:02