将数组的某些元素排序为其他数组
对于项目,我必须对包含字符串和数字的数组进行排序。该字符串用作将数字存储到哪个数组的指示符。
let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']
let talk = []
let perfo = []
let init = []
for (let i = 0; i < myArray.length; i + 2) {
if (myArray[i + 1] == 'talk') {
talk.push(myArray[i])
} else if (myArray[i + 1] == 'perfo') {
perfo.push(myArray[i])
} else if (myArray[i + 1] == 'init') {
init.push(myArray[i])
} else {}
}
预期结果:
talk [22, 42], perfo [35], init [42]
但是不知何故它似乎不适合for循环。
回答如下:您可以将所需数组作为对象,然后将值压入该对象。
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; }
将数组的某些元素排序为其他数组
对于项目,我必须对包含字符串和数字的数组进行排序。该字符串用作将数字存储到哪个数组的指示符。
let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']
let talk = []
let perfo = []
let init = []
for (let i = 0; i < myArray.length; i + 2) {
if (myArray[i + 1] == 'talk') {
talk.push(myArray[i])
} else if (myArray[i + 1] == 'perfo') {
perfo.push(myArray[i])
} else if (myArray[i + 1] == 'init') {
init.push(myArray[i])
} else {}
}
预期结果:
talk [22, 42], perfo [35], init [42]
但是不知何故它似乎不适合for循环。
回答如下:您可以将所需数组作为对象,然后将值压入该对象。
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; }
发布评论