2 回答
TA贡献1868条经验 获得超4个赞
对象与数组相同,但不是以数字作为索引,而是具有字符串,因此我们可以使用对象来重构初始数组。
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条经验 获得超4个赞
您可以获取带有所需数组的对象并将值推送给它。
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; }
添加回答
举报