关键插值Javascript

我正在阅读javascript和文章中的键插值法,它说以下是键插值法

const example = {key1: value1, key2: value2}

并向上述对象添加新值,我们将执行以下操作

const example1 = {...example, [key3]:value3}

这使o / p为:

{key1: value1, key2: value2,key3: value3}

文章说,键插值需要使用括号。

我尝试了与

const example1 = {...example, key3:value3}

它给出了相同的结果。 它们之间是否有区别,或者它们给出相同的o / p相同?

评论
quia_a
quia_a

it says following is a key interpolation const example = {key1: value1, key2: value2}

我在那里看不到任何“键插值”。

...and to add new value to the above object we will do the following const example1 = {...example, [key3]:value3} and this gives o/p as {key1: value1, key2: value2,key3: value3}.

Only if you have a variable called key3 which has the value "key3" in it.

The article says bracket is required for key interpolation.

I tried the same things as const example1 = {...example, key3:value3} and it gives the same result. Is there any difference between them or they are the same as they give the same o/p?

区别在于您是使用文字符号还是计算符号来提供属性(键)的名称:

// Literal notation, adds a property called `key` to the object
const obj1 = {key: "value"};
console.log(obj1.key); // "value"

// Computed notation, adds a property whose name comes from the
// contents of the variable `key` to the object:
const key = "propertyName";
const obj2 = {[key]: "value"};
console.log(obj2.key); // undefined, there isn't any property with that name
console.log(obj2.propertyName); // "value"
点赞
评论