【问题标题】:When should I use object property shorthand?什么时候应该使用对象属性简写?
【发布时间】:2020-04-07 03:58:29
【问题描述】:

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

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

let someObject = {
  cat,
  dog,
  bird
}

console.log(someObject);

【问题讨论】:

  • 请添加示例。我没有看到任何物体。
  • 不存在键和值相同的确切情况。这是您的数据,如果您认为它适合您的数据,那么就是这种情况。
  • 这是一个键值相同的例子:alligator.io/js/object-property-shorthand-es6
  • 你能告诉我为什么他们认为对象中的键和值是相同的吗?
  • 也许你看看这里:short hand properties

标签: javascript ecmascript-6 properties key shorthand


【解决方案1】:

来自文档:

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。

有关详细信息,请参阅

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2012-06-10
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多