我何时应该使用对象属性速记?

问题描述 投票:0回答:1

我知道当对象键和值相同时(即'cat:cat'可以重写为'cat')使用它...但是当我看代码示例时,我对哪些情况的键和值彼此相等。

let cat = 'Miaow';
let dog = 'Woof';
let bird = 'Peet peet';

let someObject = {
  cat,
  dog,
  bird
}

console.log(someObject);

//{
//  cat: "Miaow",
//  dog: "Woof",
//  bird: "Peet peet"
//}
javascript ecmascript-6 properties key shorthand
1个回答
0
投票

来自文档:

ECMAScript 2015中的新符号1

在不支持的环境中,这些符号将导致语法错误。

// Shorthand property names (ES2015)
let a = 'foo', b = 42, c = {};
let o = {a, b, c}

// Shorthand method names (ES2015)
let o = {
  property(parameters) {}
}

// Computed property names (ES2015)
let prop = 'foo'
let o = {
  [prop]: 'hey',
  ['b' + 'ar']: 'there'
}

这些表示法不适用于Internet Explorer。

有关更多信息,请参阅

© www.soinside.com 2019 - 2024. All rights reserved.