gpt4 book ai didi

javascript - 如何用另一个变量的值命名变量? JS

转载 作者:行者123 更新时间:2023-11-30 21:08:50 25 4
gpt4 key购买 nike

有没有一种方法可以根据另一个变量的值来调用一个变量,而另一个变量的值并不总是相同?

示例:

var color = 'black';
var [color] = 'whatever'; // the variable name here would be 'black'

使用原因:在 Redux 的 reducer 中,我收到一个包含特定值的操作

export default (state = INITIAL_STATE, action) => {
const { size, color, object } = action;
switch (action.type) {
case (DO_SOMETHING): {
// instead of name 'output' below, I want to have a value of 'color'
let output = object;
if (size) {
output = callExternalFunction(output, size);
}
return { ...state, [color]: output };
}

我的目标:如果可能的话,我将能够把返回变成这样:

return { ...state, [color] };

最佳答案

为什么不直接使用一个对象来保存变量名呢?例如:

var color = 'black',
variables = {};

variables[color] = 'whatever'; // { black : 'whatever' }

return { ...state, variables['black'] } // { ...state, 'whatever' }

这符合您的需求吗?也许我误解了问题

关于javascript - 如何用另一个变量的值命名变量? JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339966/

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