方法1
var arr = [20,10,33, 14, 16]; var item = 16; function choose(arr, item){ for(var i = 0; i < arr.length; i++){ if(arr[i] == item) return i; } return -1; } var end = choose(arr, item); console.log(end); var arr = [20,10,33,14, 16]; var item = 13;
方法2 reduce 方法
var arr = [20,10,33,14, 16]; var item = 13; function choose(arr, item){ var back = -1; var i = 0; arr.reduce((newarr, one)=>{ if(one == item){ back = i; } i = i + 1; },[]); return back; }
方法3
var end = choose(arr, item); console.log(end); var arr = [20,10,33,14, 16]; var item = 16; function indexOf(arr, item){ return arr.indexOf(item); } var end = indexOf(arr, item); console.log(end);
方法4
var arr = [20,10,33,14, 16]; var item = 16; function choose(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; } } var end = choose(arr, item); console.log(end);
方法4混合了1和3,只是多了一个array判断是否拥有indexOf方法,Array构造是否拥有原型方法indexOf