从所有设置为相同值的键列表创建对象的最简洁方法是什么。例如,
\n\nconst keys = [1, 2, 3, 4]\nconst value = 0\nRun Code Online (Sandbox Code Playgroud)\n\n达到目标的最简单方法是什么
\n\n{\n \xe2\x80\x9c1\xe2\x80\x9d: 0,\n \xe2\x80\x9c2\xe2\x80\x9d: 0,\n \xe2\x80\x9c3\xe2\x80\x9d: 0,\n \xe2\x80\x9c4\xe2\x80\x9d: 0\n}\nRun Code Online (Sandbox Code Playgroud)\n
您可以使用Object.fromEntries
const keys = [1, 2, 3, 4]
const value = 0
const result = Object.fromEntries(keys.map(k => [k, value]))
console.log(result)Run Code Online (Sandbox Code Playgroud)
可能应该是以下内容:
const keys = [1, 2, 3 ,4];
const value = 0;
console.log(
keys.reduce((acc, key) => (acc[key] = value, acc), {})
);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2577 次 |
| 最近记录: |