开发者

javascript array index test

开发者 https://www.devze.com 2023-01-16 20:36 出处:网络
if I have an array myArray which I am looping through: for(var i=0;i<myArray.length;i++) { if(myArray[i] == myArray[i+1])

if I have an array myArray which I am looping through:

for(var i=0;i<myArray.length;i++) {
   if(myArray[i] == myArray[i+1])
      //do something
}

Clearly, myArray[i+1] will fail on the last iteration. Short of testing if i == (myArray.length - 1), is there a clean way to not fail on that if statement and just have it evaluate to false (if myArra开发者_StackOverflowy[i+1] is out of bounds)?


Why not just iterate up to the (N-2)th item?

for(var i=0;i<myArray.length-1;i++) {
  ...

if you must iterate till the end, the only way to work in general is to explicitly check if the index is valid. Either

for (var i = 0; i < myArray.length; ++ i)
  if (i+1 != myArray.length) {
    ...

or

for (var i = 0; i < myArray.length; ++ i)
  if (!(i+1 in myArray)) {
    ...

However, if you can ensure all items in the array cannot be undefined or null, then your original code already works because an index out-of-bound will return undefined, and undefined == x will be false unless x is also undefined or null.


Look at the jquery source for some inspiration: http://github.com/jquery/jquery/blob/3a0a35288304ab5289a1/src/core.js#L632

0

精彩评论

暂无评论...
验证码 换一张
取 消