当使用x作为索引号时.要在函数中显示数组位置,数组返回undefined

When using x as index no. to show array location in a funtion, the array returns undefined

本文关键字:数组 显示 函数 位置 undefined 返回 索引      更新时间:2023-09-26

嗨,伙计们,所以我的函数返回未定义,当我使用x来表示数组的索引数在下面的代码,为什么会发生这种情况?如果有人能回答我的问题,我将不胜感激代码:

var a = 0;
var b = 0;
var z = 0;
var x = 0;
function findOutlier(integers){
  //your code here
while(x < integers.length){
 	  if(integers[x]%2 === 0){
 	  	 a = x;
 	  	 z = z + 1;
 	  }
	  else{
	  	b = x;
	  }
      x = x + 1
	  
}
if(z === 1){return integers[a]}
else{return integers[b]}
	
}
findOutlier([2,6,8,10,3]);

x <= integers.length数组从0到length-1,所以从0到length的循环意味着你要离开数组的末尾。

while(x < integers.length)代替