es6 取数组的第一个和最后一个_es6常用数组操作及技巧汇总
定義數(shù)組
const array = [1, 2, 3];
或者
const array = new Array();
array[0] = '1';
建議盡量使用第一種形式定義數(shù)組,采用new的形式在大量的數(shù)組定義時,會比較耗時。
new關鍵字的使用,除了在需要實例化一個對象,或罕見的需要延時加載數(shù)據(jù)的情況外,你基本上不需要使用new關鍵字。在Javascript里分配大量的new變量地址是一項很慢的操作,為了效率起見,你應該始終使用對象符號。
在另外一個搜索結(jié)果中,有提到這樣的一個說法:“很簡單,Array()是一個對象,[]是一個數(shù)據(jù)原型。使用new Array()系統(tǒng)每次都會新生成一個對象(瀏覽器每生成一個對象都會耗費資源去構(gòu)造他的屬性和方法),他的子集是[];個人推薦使用[],效率高。瀏覽器對于CPU很吃緊,所以很多時候要有技巧。比如數(shù)字轉(zhuǎn)換成字符只要a=a+'';就可以了,比用String效率高了很多。
檢測數(shù)組
Array.isArray([]); // true
Array.isArray(undefined); // false;
或者
array instanceof Array; // true 檢測對象的原型鏈是否指向構(gòu)造函數(shù)的prototype對象
或者
array.constructor === Array; // true
終極大招:
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
注意:typeof []; // "object" 不可以用此方法檢查!!!
常用方法
1. array.concat(array1, array2,...arrayN);
合并多個數(shù)組,返回合并后的新數(shù)組,原數(shù)組沒有變化。
const array = [1,2].concat(['a', 'b'], ['name']);
// [1, 2, "a", "b", "name"]
2. array.every(callback[, thisArg]);
檢測數(shù)組中的每一個元素是否都通過了callback測試,全部通過返回true,否則返回false。
// callback定義如下: element:當前元素值;index:當前元素下標; array:當前數(shù)組
function callback(element, index, array) {
// callback函數(shù)必須返回true或者false告知every是否通過測試
return true || false;
}
3. array.filter(callback[, thisArg]);
返回一個新數(shù)組,包含通過callback函數(shù)測試的所有元素。
// callback定義如下,三個參數(shù): element:當前元素值;index:當前元素下標; array:當前數(shù)組
function callback(element, index, array) {
// callback函數(shù)必須返回true或者false,返回true保留該元素,false則不保留。
return true || false;
}
const filtered = [1, 2, 3].filter(element => element > 1);
// filtered: [2, 3];
4. array.find(callback[, thisArg]);
返回通過callback函數(shù)測試的第一個元素,否則返回undefined,callback函數(shù)定義同上。
const finded = [1, 2, 3].find(element => element > 1);
// finded: 2
如果你需要找到一個元素的位置或者一個元素是否存在于數(shù)組中,使用Array.prototype.indexOf() 或 Array.prototype.includes()。
5. array.findIndex(callback[, thisArg]);
返回通過callback函數(shù)測試的第一個元素的索引,否則返回-1,callback函數(shù)定義同上。
const findIndex = [1, 2, 3].findIndex(element => element > 1);
// findIndex: 1
6. array.includes(searchElement, fromIndex);
includes() 方法用來判斷一個數(shù)組是否包含一個指定的值,返回 true或 false。searchElement:要查找的元素;fromIndex:開始查找的索引位置。
[1, 2, 3].includes(2, 2);
// false
7. array.indexOf(searchElement[, fromIndex = 0]);
返回在數(shù)組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。searchElement:要查找的元素;fromIndex:開始查找的索引位置。
[2, 9, 7, 8, 9].indexOf(9);
// 1
8. array.join(separator=',');
將數(shù)組中的元素通過separator連接成字符串,并返回該字符串,separator默認為","。
[1, 2, 3].join(';');
// "1;2;3"
9. array.map(callback[, thisArg]);
返回一個新數(shù)組,新數(shù)組中的每個元素都是調(diào)用callback函數(shù)后返回的結(jié)果。注意:如果沒有return值,則新數(shù)組會插入一個undefined值。
array.map由于不具有過濾的功能,因此array調(diào)用map函數(shù)時,如果array中的數(shù)據(jù)并不是每一個都會return,則必須先filter,然后再map,即map調(diào)用時必須是對數(shù)組中的每一個元素都有效。
const maped = [{name: 'aa', age: 18}, {name: 'bb', age: 20}].map(item => item.name + 'c');
// maped: ['aac', 'bbc'];
10. array.pop() 與 array.shift();
pop為從數(shù)組中刪除最后一個元素,并返回最后一個元素的值,原數(shù)組的最后一個元素被刪除。數(shù)組為空時返回undefined。
[1, 2, 3].pop();
// 3
shift刪除數(shù)組的第一個元素,并返回第一個元素,原數(shù)組的第一個元素被刪除。數(shù)組為空返回undefined。
const shifted = ['one', 'two', 'three'].shift();
// shifted: 'one'
11. array.push(element1, element2, ....elementN) 與 array.unshift(element1, element2, ...elementN);
push是將一個或多個元素添加到數(shù)組的末尾,并返回新數(shù)組的長度; unshift將一個或多個元素添加到數(shù)組的開頭,并返回新數(shù)組的長度。唯一的區(qū)別就是插入的位置不同。
const arr = [1, 2, 3];
const length = arr.push(4, 5);
// arr: [1, 2, 3, 4, 5]; length: 5
push和unshift方法具有通用性,通過call()或者apply()方法調(diào)用可以完成合并兩個數(shù)組的操作。
const vegetables = ['parsnip', 'potato'];
const moreVegs = ['celery', 'beetroot'];
// 將第二個數(shù)組融合進第一個數(shù)組
// 相當于 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
或者
[].push.apply(vegetables, moreVegs);
// vegetables: ['parsnip', 'potato', 'celery', 'beetroot']
12. array.reduce(callback[, initialValue]);
對數(shù)組中的每個元素(從左到右)執(zhí)行callback函數(shù)累加,將其減少為單個值。
const total = [0, 1, 2, 3].reduce((sum, value) => {
return sum + value;
}, 0);
// total is 6
const flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => {
return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]
// initialValue累加器初始值, callback函數(shù)定義:
function callback(accumulator, currentValue, currentIndex, array) {
}
accumulator代表累加器的值,初始化時,如果initialValue有值,則accumulator初始化的值為initialValue,整個循環(huán)從第一個元素開始;initialValue無值,則accumulator初始化的
值為數(shù)組第一個元素的值,currentValue為數(shù)組第二個元素的值,整個循環(huán)從第二個元素開始。initialValue的數(shù)據(jù)類型可以是任意類型,不需要跟原數(shù)組內(nèi)的元素值類型一致。
const newArray = [{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].reduce((arr, element) => {
if (element.age >= 2) {
arr.push(element.name);
}
return arr; // 必須有return,因為return的返回值會被賦給新的累加器,否則累加器的值會為undefined。
}, []);
// newArray is ["bb", "cc"];
上面代碼的同等寫法:
const newArray = [{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].filter(element => element.age >= 2).map(item => item.name);
// newArray is ["bb", "cc"];
對于reduce的特殊用法,其實類似于省略了一個變量初始化步驟,然后通過每次的callback的返回修改該變量,最后返回最終變量值的過程,類似于一個變量聲明 + 一個forEach執(zhí)行過程。
const newArray = [];
[{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].forEach(item => {
if (item.age >=2) {
newArray.push(item.name);
}
});
13. array.reverse();
將數(shù)組中元素的位置顛倒。
['one', 'two', 'three'].reverse();
// ['three', 'two', 'one'],原數(shù)組被翻轉(zhuǎn)
14. array.slice(begin, end)
返回一個新數(shù)組,包含原數(shù)組從begin 到 end(不包含end)索引位置的所有元素。
const newArray = ['zero', 'one', 'two', 'three'].slice(1, 3);
// newArray: ['one', 'two'];
15. array.some(callback[, thisArg]);
判斷數(shù)組中是否包含可以通過callback測試的元素,與every不同的是,這里只要某一個元素通過測試,即返回true。callback定義同上。
[2, 5, 8, 1, 4].some(item => item > 6);
// true
16. array.sort([compareFunction]);
對數(shù)組中的元素進行排序,compareFunction不存在時,元素按照轉(zhuǎn)換為的字符串的諸個字符的Unicode位點進行排序,慎用!請使用時一定要加compareFunction函數(shù),而且該排序是不穩(wěn)定的。
[1, 8, 5].sort((a, b) => {
return a-b; // 從小到大排序
});
// [1, 5, 8]
17. array.splice(start[, deleteCount, item1, item2, ...]);
通過刪除現(xiàn)有元素和/或添加新元素來更改一個數(shù)組的內(nèi)容。start:指定修改的開始位置;deleteCount:從 start位置開始要刪除的元素個數(shù);item...:要添加進數(shù)組的元素,從start 位置開始。
返回值是由被刪除的元素組成的一個數(shù)組。如果只刪除了一個元素,則返回只包含一個元素的數(shù)組。如果沒有刪除元素,則返回空數(shù)組。
如果 deleteCount 大于start 之后的元素的總數(shù),則從 start 后面的元素都將被刪除(含第 start 位)。
const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
const deleted = myFish.splice(2, 0, 'drum'); // 在索引為2的位置插入'drum'
// myFish 變?yōu)?["angel", "clown", "drum", "mandarin", "sturgeon"],deleted為[]
小結(jié)
push、 shift、 pop、 unshift、 reverse、 sort、 splice方法會對原來的數(shù)組進行修改,其他的數(shù)組操作方法只有返回值不同,對原數(shù)組都沒有影響,即原數(shù)組不變。
小結(jié)
在看vue代碼的時候,發(fā)現(xiàn)vue教程里面Array.apply(null, {length: 20})的用法,apply一直以為第二個參數(shù)只能是[]或者Arguments這樣的類數(shù)組,了解了下發(fā)現(xiàn){length: 20}也是類數(shù)組。 帶有l(wèi)ength屬性的obj在apply函數(shù)里都被認定為類數(shù)組。可以理解為這里的{length: 20}會被默認為是一個數(shù)組了。下圖的slice操作是只能在數(shù)組對象執(zhí)行的操作,所以這里是一個數(shù)組。
看了下代碼,apply生成的數(shù)組里面被初始化為了undefined,就是生成了長度為5的數(shù)組,而且數(shù)組的每個元素都被初始化為了undefined。
Array(5)和new Array(5)調(diào)用效果是一致的。官網(wǎng)解釋為:當把構(gòu)造函數(shù)作為函數(shù)調(diào)用,不使用 new 運算符時,它的行為與使用 new 運算符調(diào)用它時的行為完全一樣。 它們也生成了長度為5的數(shù)組,但是是個空數(shù)組,數(shù)組中的每個元素都沒有初始化。
為什么要這么寫?
map函數(shù)并不會遍歷數(shù)組中沒有初始化或者被delete的元素(有相同限制還有forEach, reduce方法)。
Array.apply(null, { length: 5 }) 是用來初始化一個長度為5,每項的初始值都是undefined的數(shù)組。
render (createElement) {
return createElement('div',
// 這里apply第一個對象為null, 當調(diào)用的函數(shù)不需要this對象時,可以傳null,在es5之前瀏覽器會將null代表的this指向window。es5之后,瀏覽器不會再將this指向window。這里傳null是因為Array構(gòu)造函數(shù)會重新創(chuàng)建this,不需要傳入this對象。
Array.apply(null, { length: 20 }).map(function () {
// 這里如果用Array(2)的形式,map的回調(diào)函數(shù)不會被執(zhí)行
return createElement('p', 'hi')
})
)
}
總結(jié)
以上是生活随笔為你收集整理的es6 取数组的第一个和最后一个_es6常用数组操作及技巧汇总的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jquery复制粘贴
- 下一篇: ObjectARX2010二次开发之 -