如何将数组拆分为奇数数组和偶数数组

问题描述 投票:0回答:4

我有一个问题,将数组拆分为单独的数组奇数和偶数。我做的是:

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

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)

谢谢

javascript reactjs
4个回答
2
投票

您必须使用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"] }

0
投票

正确的条件是if ( ( allData[i] % 2 ) === 0)

试试控制台:

4 % 2
4 % 3

0
投票

你可以使用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 );

0
投票

而不是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)});
© www.soinside.com 2019 - 2024. All rights reserved.