[英]Unable to compare two values in an array for javascript
我试图看看是否可以让我的函数确定函数中存在的数组中的“奇怪的人”。 具体来说,在我获取字符串后,将其转换为数字并将其推入数组中-我希望它能够遍历输出数组并返回数字的索引为“奇数输出”(即“ 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
在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]);
您可能会发现更容易将问题分解为较小的单元。
// 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
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个数组:一个为奇数,一个为偶数,并比较长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.