【发布时间】:2016-03-20 23:07:37
【问题描述】:
我正在尝试查看是否可以让我的函数来确定位于函数内的数组中的“奇怪的人”。具体来说,在我获取一个字符串后,将其转换为数字并将其推送到一个数组中——我希望它能够遍历输出数组并返回哪个数字的索引是“奇怪的人”(即“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
【问题讨论】:
-
notSame("5 7 9 2 1" );应该返回 3
标签: javascript arrays loops for-loop