是否可以这样做:
const foo = [1, 2];
const bar = {
a: foo[0],
b: foo[1],
c: 'something else not in array'
};
作为单个语句,无需声明 foo
?
例如,数组可能是
的结果"1, 2".split(', ')
并且您想避免临时变量声明,请使用 "1"
和"2"
作为新对象中两个属性(可能不是唯一的属性)的值。
我可以想象这样的事情,尽管由于各种原因都无效:
const bar { a, b, c: 'something else not in array' } = [1, 2];
或
const bar { a:[0], b:[1], c: 'something else not in array' } = [1, 2];
编辑: 我发现的最接近的(不使用 IIFE)是
Object.assign({c: 'something else not in array'}, [1, 2])
它的缺点是,您得到的不是名为“a”和“b”的属性,而是名为“0”和“1”的属性:
{0: 1, 1: 2, c: "something else not in array"}
最佳答案
是的,使用 IIFE:
const bar = (([a, b]) => ({ a, b, c: "other props" }))([1, 2]);
关于javascript - 是否可以通过解构从数组创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771129/