我有一個逗號分隔的串列
var arr = [1,2,3,4]
并希望它是:
var new_arr = [
{x:1, y:2},
{x:3, y:4}
]
苦苦思索如何完成鍵/值更改。
uj5u.com熱心網友回復:
您可以使用Array.reduce()回傳所需的結果。
如果元素索引是偶數,則在結果中添加一個新專案,如果不是則跳過它。
const input = [1,2,3,4]
const result = input.reduce((acc, el, idx, arr) => {
return (idx % 2) ? acc : [...acc, { x: el, y: arr[idx 1]} ];
}, []);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
您可以執行以下操作:
首先,您映射您的陣列,如果modulus value您當前的迭代索引不等于 0,則回傳一個空物件(然后您將filter在最后輸出),否則回傳一個新物件,該物件在迭代中獲取當前元素to y,以及陣列的前一個元素(使用index) tox
const x = [1,2,3,4,5]
const g = x.map((el, i) => {
if(i%2) {
return {
x: x[i - 1],
y: el
}
}
return {}
}).filter(t => Object.keys(t).length)
console.log(g)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487431.html
標籤:javascript 数组 目的
