我有一個非常簡單的代碼塊:
function toObj(i){
return {
i: i
};
}
numObj=s=>s.map(toObj)
當我將一組數字傳遞給 numObj 時,我希望鍵和值與傳入的引數相匹配。 例如,我希望得到以下結果:
numObj([1, 2, 3, 4]) => [{1: 1}, {2: 2}, {3: 3}, {4: 4}]
相反,我得到了這個:
numObj([1, 2, 3, 4]) => [{i: 1}, {i: 2}, {i: 3}, {i: 4}]
如何將回傳物件的鍵設定為傳入的引數?
uj5u.com熱心網友回復:
使用計算屬性名稱從值創建鍵:
const toObj = i => ({ [i]: i })
const numObj = arr => arr.map(toObj)
const result = numObj([1, 2, 3, 4])
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315806.html
標籤:javascript 数组 目的
上一篇:從陣列物件的鍵創建一個新陣列
