首页 > 解决方案 > 什么时候应该使用对象属性简写?

问题描述

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

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

let someObject = {
  cat,
  dog,
  bird
}

console.log(someObject);

标签: javascriptecmascript-6propertieskeyshorthand

解决方案


从文档:

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。

有关详细信息,请参阅


推荐阅读