1 indexOf()和lastIndexOf
indexOf():接收兩個參數:要查找的項和(可選的)表示查找起點位置的索引。其中, 從數組的開頭(位置 0)開始向后查找。
書寫格式:arr.indexof( 5 )
lastIndexOf:接收兩個參數:要查找的項和(可選的)表示查找起點位置的索引。其中, 從數組的末尾開始向前查找。
書寫格式:arr.lastIndexOf( 5,4 )
var arr = [1,3,5,7,7,5,3,1]; console.log(arr.indexOf(5)); //2 console.log(arr.lastIndexOf(5)); //5 console.log(arr.indexOf(5,2)); //2 console.log(arr.lastIndexOf(5,4)); //2 console.log(arr.indexOf("5")); //-1
2 forEach()
forEach():對數組進行遍歷循環,對數組中的每一項運行給定函數。這個方法沒有返回值。參數都是function類型,默認有傳參,參數分別為:遍歷的數組內容;第對應的數組索引,數組本身。
書寫格式:arr.forEach()
var arr = [1, 2, 3, 4, 5]; arr.forEach(function(x, index, a){ console.log(x + '|' + index + '|' + (a === arr)); }); // 輸出為: // 1|0|true // 2|1|true // 3|2|true // 4|3|true // 5|4|true
3 map()
map():指“映射”,對數組中的每一項運行給定函數,返回每次函數調用的結果組成的數組。
書寫格式:arr.map()
var arr = [1, 2, 3, 4, 5]; var arr2 = arr.map(function(item){ return item*item; }); console.log(arr2); //[1, 4, 9, 16, 25]
4 filter()
filter():“過濾”功能,數組中的每一項運行給定函數,返回滿足過濾條件組成的數組。
書寫格式:arr.filter()
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var arr2 = arr.filter(function(x, index) { return index % 3 === 0 || x >= 8; }); console.log(arr2); //[1, 4, 7, 8, 9, 10]
5 every()
every():判斷數組中每一項都是否滿足條件,只有所有項都滿足條件,才會返回true。
書寫格式:arr.every()
var arr = [1, 2, 3, 4, 5]; var arr2 = arr.every(function(x) { return x < 10; }); console.log(arr2); //true var arr3 = arr.every(function(x) { return x < 3; }); console.log(arr3); // false
6 some()
some():判斷數組中是否存在滿足條件的項,只要有一項滿足條件,就會返回true。
書寫格式:arr.some()
var arr = [1, 2, 3, 4, 5]; var arr2 = arr.some(function(x) { return x < 3; }); console.log(arr2); //true var arr3 = arr.some(function(x) { return x < 1; }); console.log(arr3); // false