了解计算的属性(方括号) [英] Understanding computed properties (square brackets)

查看:43
本文介绍了了解计算的属性(方括号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是无法绕过计算属性",我在Google上四处搜寻,但没有太大帮助,我正在关注的网站是这样说的,但是有人能说得更清楚吗?我知道这是对我的解释,但我仍然无法真正理解它想告诉我的内容.您可以尝试用简单的单词"说出来吗?

I simply can't wrap my head around "computed properties", I have googled around but it didn't help much, the website I am following says this, but could anyone make it clearer? I know it's spelled out to me but I still couldn't really understand what it's trying to tell me. Could you try to say it in "simple words"?

我们可以在对象文字中使用方括号.那叫计算属性.

例如:

let fruit = prompt("Which fruit to buy?", "apple");

let bag = {
  [fruit]: 5, // the name of the property is taken from the variable fruit
};

alert( bag.apple ); // 5 if fruit="apple"

计算属性的含义很简单: [fruit] 表示属性名称应取自 fruit .

The meaning of a computed property is simple: [fruit] means that the property name should be taken from fruit.

因此,如果访客输入苹果" ,则 bag 将变为 {apple:5} .

So, if a visitor enters "apple", the bag will become {apple: 5}.

我无法理解的部分是

alert( bag.apple ); // 5 if fruit="apple" 

推荐答案

您正在将提示的值保存在名为 fruit 的变量中.在这种情况下,它默认为苹果".

You're saving the value of the prompt in a variable called fruit. In this case, it defaults to "apple".

然后您要声明另一个变量 bag . bag 具有一个属性,这里是 [fruit] .这将在运行时求值为 fruit 的值,从而有效地进行声明

You're then declaring another variable, bag. bag has one property, which here is [fruit]. This will evaluate to the value of fruit at runtime, effectively making the declaration

let bag = {
  'apple': 5
};

然后,警报功能将警报 bag.apple 的值. bag.apple 之所以具有值,是因为在声明 bag 变量和 fruit 'apple'.

The alert function will then alert the value of bag.apple. bag.apple has a value because you set bag[fruit] to be 5 when you declared the bag variable, and fruit is 'apple'.

这篇关于了解计算的属性(方括号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆