我在网络上发现了一些混乱的代码,我无法理解:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
[action.subreddit]
是做什么的?我以为对象键必须是字符串,但这似乎是一个数组?
我希望能够从机械上理解这个代码是如何工作的。
谢谢!
我在网络上发现了一些混乱的代码,我无法理解:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
[action.subreddit]
是做什么的?我以为对象键必须是字符串,但这似乎是一个数组?
我希望能够从机械上理解这个代码是如何工作的。
谢谢!
这不是一个数组作为键,而是使用变量(/计算属性)作为键的ES6方式。 请考虑以下示例:
var a = "foo";
function getKey() {
return "myKey";
}
var obj = {
[a] : "bar",
[getKey()] : "baz"
};
console.log(obj.foo); // bar
console.log(obj.myKey) // baz
因此,[action.subreddit]
将键的名称设置为action.subreddit
所持有的任何值。
console.log(obj[a]); // bar
。 - Michelangelo