js练习题之查找数组中的位子

输出描述:

如果数组中存在 item,则返回元素在数组中的位置,否则返回 -1

输入例子:

indexOf([ 1, 2, 3, 4 ], 3)

输出例子:

2

  

function indexOf(arr, item) {
  if (Array.prototype.indexOf){
      return arr.indexOf(item);
  } else {
      for (var i = 0; i < arr.length; i++){
          if (arr[i] === item){
              return i;
          }
      }
  }     
  return -1;
}

  

原文地址:https://www.cnblogs.com/mengluo/p/4891669.html