深刻淺出JavaScript:ES6數組方法

ES6數組方法

如下方法添加到了Array.prototype對象上(isArray除外)數組

indexOf

相似字符串的indexOf()方法瀏覽器

stringObject.indexOf(searchvalue,fromindex)
var data = [2, 5, 7, 3, 5];
console.log(data.indexOf(5, "x")); // 1 ("x"被忽略)
console.log(data.indexOf(5, "3")); // 4 (從3號位開始搜索)
console.log(data.indexOf(4)); // -1 (未找到)
console.log(data.indexOf("5")); // -1 (未找到,由於5 !== "5")

lastIndexOf

相似indexOf()方法(順序相反)函數

forEach

Array在ES5新增的方法中,參數都是function類型,默認有傳參(遍歷的數組內容,對應的數組索引,數組自己)this

[].forEach(function(value, index, array) {
    // ...
});

forEach方法 遍歷數組元素prototype

var colors = ['red', 'green', 'blue'];
colors.forEach(function(color) { 
    console.log(color);
});

forEach除了接受一個必須的回調函數參數,還能夠接受一個可選的上下文參數(改變回調函數裏面的this指向)(第2個參數)若是這第2個可選參數不指定,則使用全局對象代替(在瀏覽器是爲window),嚴格模式下甚至是undefinedcode

array.forEach(callback,[ thisObject])

map

映射(一一對應)。[].map();基本用法跟forEach方法相似:對象

array.map(callback,[ thisObject]);

可是callback須要有return值(若是沒有,就像會返回undefined)索引

var a1 = ['a', 'b', 'c'];
var a2 = a1.map(function(item) { 
    return item.toUpperCase(); 
});
console.log(a2); // logs A,B,C

filter

過濾篩選(callback在這裏擔任的是過濾器的角色,當元素符合條件,過濾器就返回true,而filter則會返回全部符合過濾條件的元素)。字符串

array.filter(callback,[ thisObject]);

指數組filter後,返回過濾後的新數組。用法跟map類似回調函數

var a1 = ['a', 10, 'b', 20, 'c', 30];
var a2 = a1.filter(function(item) { 
    return typeof item == 'number'; 
});
console.log(a2); // logs 10,20,30

every(且)

every(callback[, thisObject])當數組中每個元素在callback上被返回true時就返回true。

function isNumber(value){ 
    return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.every(isNumber)); // logs false

some(或)

some(callback[, thisObject]) 只要數組中有一項在callback上被返回true,就返回true。

function isNumber(value){ 
return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.some(isNumber)); // logs true
var a3 = ['1', '2', '3'];
console.log(a3.some(isNumber)); // logs false

reduce(從左到右累加)

對數組中的全部元素調用指定的回調函數。
該回調函數的返回值爲累積結果,而且此返回值在下一次調用該回調函數時做爲參數提供。

var a = [10, 20, 30];
var total = a.reduce(function(first, second) { 
    return first + second; 
}, 0);
console.log(total) // Prints 60

reduceRight(從右到左累加)

reduce的做用徹底相同,惟一的不一樣是,reduceRight是從右至左遍歷數組的元素。

Array構造器上的isArray

Array.isArray直接寫在了Array構造器上,而不是prototype對象上。
Array.isArray會根據參數的[[Class]]內部屬性是不是」Array」返回true或false.

Array.isArray("NO U")
falseArray.isArray(["NO", "U"])// true

Array.prototype.slice.call

真實數組具備slice方法,能夠對數組進行淺複製(不影響原數組),返回的依然是數組。
相似數組雖然有length屬性,可使用for循環遍歷,卻不能直接使用slice方法,會報錯!可是經過Array.prototype.slice.call則不會報錯,自己(相似數組)被從頭至尾slice複製了一遍——變成了真實數組!

將相似數組的對象(好比arguments)轉換爲真實的數組

Array.prototype.slice.call(arguments)
相關文章
相關標籤/搜索