有没有一种方法可以根据另一个变量的值来调用一个变量,而另一个变量的值并不总是相同?
示例:
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/