亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

javascript將數組的一些元素排序到另一個數組中

javascript將數組的一些元素排序到另一個數組中

30秒到達戰場 2022-07-21 22:28:43
對于一個項目,我必須對包含字符串和數字的數組進行排序。該字符串用作應將數字存儲到哪個數組中的指示符。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 循環。
查看完整描述

2 回答

?
MYYA

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]

// }


查看完整回答
反對 回復 2022-07-21
?
慕無忌1623718

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; }


查看完整回答
反對 回復 2022-07-21
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號