【问题标题】:Identifier has been declared已声明标识符
【发布时间】:2021-11-17 13:05:23
【问题描述】:

因为我是初学者,所以不知道那里发生了什么。你能帮我/解释一下发生了什么吗?

它适用于除“位置”之外的所有属性,它说:

property has been declared

'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);

【问题讨论】:

  • 如果您在window 范围内执行此操作,则有window.location
  • 请注意,您仍然可以使用解构,您只需将 location 属性别名为未保留的 const {location:locn} = restaurant; (现在有一个变量 locn 与您的值)

标签: javascript console.log


【解决方案1】:

正如您的控制台所说:不能将 location 属性分配给新变量,因为它之前已经声明过。

这是因为您的 Javascript 在环境(浏览器)中运行,并且该环境中有一些变量和方法。

您可以通过以下方式查看:

console.log(window)

结果是:

Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}

如您所见,位置是存在于您的窗口对象中的预定义属性,因此在global scope 中声明新的location 属性是导致问题的原因。

如果您熟悉 Javascript 中的scopes,您可以简单地将您的代码 sn-p 包装到一个函数中以使其正常工作:

'use strict';

function logLocation(){
   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);
}

logLocation()

【讨论】:

    【解决方案2】:

    如果您在浏览器的控制台中使用此代码,很自然会收到此错误,因为 location 是 Location 对象的保留名称,该对象包含有关当前页面 URL 的信息。

    见:https://www.w3schools.com/jsref/obj_location.asp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2021-03-28
      相关资源
      最近更新 更多