gpt4 book ai didi

javascript - JS中的括号以获取值(value)

转载 作者:行者123 更新时间:2023-12-03 23:55:59 24 4
gpt4 key购买 nike

这有效:

  handleOnChange(e) {
this.setState({[e.target.id]: e.target.value});
}
e.target.id用方括号( [ ])包裹,而 e.target.value则不用。

我也可以在方括号中写 e.target.value,它可以工作,但是如果我从 e.target.id中删除方括号,我的代码将无法工作。为什么?

我做了一些研究,认为这是因为 Computed Property Names (虽然我不确定),但是随后出现了一个问题,为什么需要计算 e.target.id的属性,而无需计算 e.target.value?我认为它们都是简单的值(value)观。

最佳答案

why does the property of e.target.id needs to be computed while e.target.value does not?



右侧始终是一个值(并且一直都是)。

从历史上看,左侧是字符串或标识符。可以在其中放置表达式(计算出的属性名称)是一项新功能。

const foo = "bar";
// Here the property name is foo because it is an identifier
const obj = {
foo: foo
};
console.log(obj);

// Here the property name is foo because it is a string
const obj2 = {
"foo": foo
};
console.log(obj2);

// Here the property name is bar because it computed by evauating the constant
const obj3 = {
[foo]: foo
};
console.log(obj3);


// Here the property name is barbar because it computed by evauating function call that returns a template string that uses the constant twice
function blah() {
return `${foo}${foo}`;
}
const obj4 = {
[blah()]: foo
};
console.log(obj4);


//This is the same as the previous example except that because the right hand side is always a value, wrapping the code in square brackets means it is treated as an array literal (as opposed to being a computed property which is what square brackets mean on the left hand side)
function blah() {
return `${foo}${foo}`;
}
const obj5 = {
[blah()]: [foo]
};
console.log(obj5);

关于javascript - JS中的括号以获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59648939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com