javascript将数组的一些元素排序到另一个数组中

对于一个项目,我必须对包含字符串和数字的数组进行排序。该字符串用作应将数字存储到哪个数组中的指示符。


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 循环。


30秒到达战场
浏览 119回答 2
2回答

MYYA

对象与数组相同,但不是以数字作为索引,而是具有字符串,因此我们可以使用对象来重构初始数组。let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']let arrays = {}for (let i = 0; i < myArray.length; i+=2) {&nbsp; const arrayName = myArray[i+1];&nbsp;&nbsp;&nbsp; if (arrays[arrayName]) {&nbsp; &nbsp; arrays[arrayName].push(myArray[i])&nbsp; } else {&nbsp; &nbsp; arrays[arrayName] = [myArray[i]]&nbsp; }}console.log(arrays);// [object Object] {//&nbsp; init: [35],//&nbsp; perfo: [31],//&nbsp; talk: [22, 42]// }

慕无忌1623718

您可以获取带有所需数组的对象并将值推送给它。let data = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk'],&nbsp; &nbsp; talk = [],&nbsp; &nbsp; perfo = [],&nbsp; &nbsp; init = [],&nbsp; &nbsp; temp = { talk, perfo, init },&nbsp; &nbsp; i = 0;while (i < data.length) {&nbsp; &nbsp; let [value, key] = data.slice(i, i += 2);&nbsp; &nbsp; temp[key].push(value);}console.log(talk);console.log(perfo);console.log(init);.as-console-wrapper { max-height: 100% !important; top: 0; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript