无法比较javascript数组中的两个值

时间:2016-03-20 23:07:38

标签: javascript arrays loops for-loop

我试图看看我是否可以通过我的功能确定"奇怪的人"在数组内生活的功能。具体来说,在我取一个字符串后,将其转换为数字并将其推入一个数组 - 我希望它能够循环输出数组并返回索引,其中的数字是"奇怪的是#34 ; (即" 2 2 2 2 4 6 8 1"应返回索引7,因为它是唯一的奇数)。但是,当函数面临我在代码中列出的两种情况时,我无法弄清楚如何返回索引。

function notSame(numbers){
  var notString = parseInt(numbers.replace(/\s+/g, ''), 10),
  sNumber = notString.toString(),
  output =[];

console.log(sNumber);

for(var i = 0; i < sNumber.length; i+=1) {
    output.push(+sNumber.charAt(i));    

}

for(var num1 = 0; num1 < output.length; num1++) {
    for(var num2 = 1; num2 < output.length; num2++) {
    if(output[num1] % output[num2] === 1) {  
        return num1;
        }
    }
  }
}

notSame("2 2 2 2 4 6 8 1"); /// Situation 1: should output index 7 as it is the only odd number
notSame("5 7 9 2 1" ); ///Situation 2: should output index 4 as it is the only even number 

3 个答案:

答案 0 :(得分:0)

output数组中有整数后,

 // test the first three array members
  var test = Math.abs(output[0])%2 + Math.abs(output[1])%2 + Math.abs(output[2])%2;
 // if the sum of the mods of the first three integers in the 
 // array is more than 1, the array is mostly odd numbers, hence 
 // the odd one out will be even, else it will be odd
  var outlierIsOdd = test >= 2 ? false : true;
 // find the odd one out and return it's index
  return output.indexOf(output.filter(function(e){
    return (Math.abs(e)%2 === +outlierIsOdd);
  })[0]);

答案 1 :(得分:0)

您可能会发现将问题分解为更小的单位更容易。

// return an array from a string
function toArray(str) { return str.split(' '); }

// return the element if it's even
function even(el) { return el % 2 === 0; }

// return the index of either true/false
function getIndex(arr, flag) { return arr.indexOf(flag); }

// count how many instances of true are in the array
function count(arr) {
  return arr.filter(function (el) {
    return el;
  }).length;
}

function check(str) {

  // return an array of true/false values
  var evens = toArray(str).map(even);

  // if there is more than 1 true value in `evens`
  // return the index of false from the array
  // otherwise return the index of the only true element
  return count(evens) > 1 ? getIndex(evens, false) : getIndex(evens, true);
}

check('2 2 2 2 4 6 8 1'); // 7
check('5 7 9 2 1'); // 3
check('2 5 2 6 6'); // 1
check('7 7 7 9 1 3 8 1 5') // 6

DEMO

答案 2 :(得分:0)

function notSame(string) {
  var even = [];
  var odd = [];
  string.split(" ").forEach(function(e, i) {
    string.split(" ")[i] % 2 ? odd.push(i) : even.push(i);
  })
  even > odd ? document.write(even) : document.write(odd);
}

notSame("2 2 2 2 4 6 8 1");

用索引填满2个数组: 一个用于赔率,一个用于平均值并比较长度。