2 回答

TA貢獻1868條經(jīng)驗 獲得超4個贊
對象與數(shù)組相同,但不是以數(shù)字作為索引,而是具有字符串,因此我們可以使用對象來重構(gòu)初始數(shù)組。
let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']
let arrays = {}
for (let i = 0; i < myArray.length; i+=2) {
const arrayName = myArray[i+1];
if (arrays[arrayName]) {
arrays[arrayName].push(myArray[i])
} else {
arrays[arrayName] = [myArray[i]]
}
}
console.log(arrays);
// [object Object] {
// init: [35],
// perfo: [31],
// talk: [22, 42]
// }

TA貢獻1744條經(jīng)驗 獲得超4個贊
您可以獲取帶有所需數(shù)組的對象并將值推送給它。
let data = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk'],
talk = [],
perfo = [],
init = [],
temp = { talk, perfo, init },
i = 0;
while (i < data.length) {
let [value, key] = data.slice(i, i += 2);
temp[key].push(value);
}
console.log(talk);
console.log(perfo);
console.log(init);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
舉報