簡體   English   中英

如何將數組拆分為奇數數組和偶數數組

[英]How to split an Array into Odd Array and Even Array

我在將數組拆分為單獨的數組Odd和Even時遇到問題。 我所做的是:

componentDidMount() {
 axios.get( `${this.props.cmsUrl}types/genres`)
 .then(response => { if ( response.data !== undefined ) {

  let even = [];
  let odd = [];
  let allData = ["a", "b", "c", "d", "e", "f", "g", "h", ];

  for (var i = 0; i < allData.length; ++i) {
    if ( ( allData[i] % 2 ) === 0) { 
      even.push(allData[i]);
    } 
    else { 
      odd.push(allData[i]); 
    }
  };
  console.log("allData : ",allData);
  console.log("even : ",even);
  console.log("even : ",odd);
 }}
)
}

我真正期望的是

allData = [a, b, c, d]
odd = [a , c]
even = [b, d]

但是真正發生的是

allData = even 
odd = empty array

這是我的問題( allData[i] % 2 ) === 1 => ( allData[i] % 2 ) === 1

console.log是:

  allData :  (8) ["a", "b", "c", "d", "e", "f", "g", "h"]0: "a"1: "b"2: "c"3: 
  "d"4: "e"5: "f"6: "g"7: "h"length: 8__proto__: Array(0)
    details.js:56 even :  []length: 0__proto__: Array(0)
    details.js:57 odd :  (8) ["a", "b", "c", "d", "e", "f", "g", "h"]0: 
   "a"1: "b"2: "c"3: "d"4: "e"5: "f"6: "g"7: "h"length: 8__proto__: Array(0)

謝謝

您必須使用charCodeAt方法,因為allData是一個字符串數組,而不是數字數組。

這是您的問題的解決方案:

if ( ( allData[i].charCodeAt(0) % 2 ) === 0) { your code }

=================

正如Thomas Scheffer提到的那樣,看來您希望基於字符索引而不是其值進行排序。

因此,如果您要基於索引進行排序,則必須編寫:

if ( ( i % 2 ) === 0) { your code }

它像這樣轉換:

allData = ["b","f","z","w"] => { odd=["f","w"], even=["b","z"]  }

但是如果您想根據字符值進行排序,則必須編寫:

if ( ( allData[i].charCodeAt(0) % 2 ) === 0) { your code }

它像這樣轉換:

allData = ["b","f","z","w"] => { odd=["w"] , even=["b","f","z"] }

正確的條件是if ( ( allData[i] % 2 ) === 0)

在控制台中嘗試:

4 % 2
4 % 3

代替for循環,可以使用filter方法

 /*ES6*/ let evenArray = result.filter((a,i) => i%2); let oddArray = result.filter((a,i) => !(i%2)); /*ES5*/ let evenArray = result.filter(function(a,i){return i%2}); let oddArray = result.filter(function(a,i){return !(i%2)}); 

您可以使用Array.prototype.reduce

 let allData = [ "a", "b", "c", "d", "e", "f", "g", "h" ]; const { even, odd } = allData.reduce((acc, val, index) => { const key = index % 2 ? 'odd' : 'even'; return { ...acc, [key]: acc[key].concat(val), }; }, { odd: [], even: [] }); console.log( 'even', even ); console.log( 'odd', odd ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM