新手或從其餘語言轉前端的同窗剛接觸js時,涉及到的數組循環通常都是for、while,以for居多。前端
forEach
和map
好比輸入某個const a = [1,2,3]
,要輸出數組[2,3,4]
。for操做會像下面這樣(返回新數組)數組
const a = [1,2,3];
const b = [];
for (let i = 0; i < a.length; i++) {
b[i] = a[i] + 1;
}
console.log(b); // [2,3,4]
複製代碼
或(修改原數組)函數
const a = [1,2,3];
for (let i = 0; i < a.length; i++) {
a[i] += 1;
}
console.log(a); // [2,3,4]
複製代碼
而ES5新增的數組方法forEach
與map
也能夠更優雅的實現測試
(返回新數組)spa
const a = [1,2,3];
const b = a.map(value => value + 1);
複製代碼
或(修改原數組)code
const a = [1,2,3];
a.forEach((value,index) => a[index] = value + 1);
複製代碼
some
和every
或許有人會說forEach
不能中斷,達不到for循環中的break
的效果ip
即get
const a = [1,2,3];
for (let index = 0; index < a.length; index ++) {
if (index === 1) {
break;
}
// do something
}
複製代碼
forEach
確實不能,可是ES5新增的數組方法some
和every
均可以實現相似的效果。回調函數
some
方法的做用爲:若是數組中至少有一個元素知足測試函數,則返回 true
,而且退出循環。console
every
方法的做用爲: 若是數組中的每一個元素都知足測試函數,則返回 true
;不然返回 false
, 並退出循環。
const a = [1,2,3];
a.some((value, index) => {
if (index === 1) {
return true; // 此處達到break的效果
}
// do something
return false;
})
const a = [1,2,3];
a.every((value, index) => {
if (index === 1) {
return false; // 此處達到break的效果
}
// do something
return true;
})
複製代碼
至於for中的continue
,用forEach
實現就行了
const a = [1,2,3];
a.forEach(value => {
if (value === 3) return; // 此處達到continue的效果
// dosomething
})
複製代碼
filter
過濾a中的偶數,for的實現方式(返回新數組)
const a = [1,2,3];
const b = [];
for(let index = 0; index < a.length; index++) {
if (a[index] % 2 === 0) {
b.push(a[index]);
}
}
複製代碼
ES5新增的數組方法filter
也能夠更優雅的作到
const a = [1,2,3];
const b = a.filter(value => value % 2 === 0);
複製代碼
reduce
和reduceRight
某些場景下可能須要對數組的每一項都進行某種操做。好比獲取數組a
中元素的和。
for的實現方式
const a = [1,2,3];
let sum = 0;
for(let index = 0; index < a.length; index++) {
sum += a[i];
}
複製代碼
ES5新增的數組方法reduce
也能夠實現,
其做用爲: 從左到右爲每一個數組元素執行一次回調函數,並把上次回調函數的返回值放在一個暫存器中傳給下次回調函數,並返回最後一次回調函數的返回值。
const a = [1,2,3];
const sum = a.reduce((prev, next) => prev + next, 0)
複製代碼
數組方法還有個reduceRight
,做用跟reduce
近似,不過是從右往左執行回調函數
findIndex
for循環獲取第一個偶數的index
const a = [1,2,3];
let i = -1;
for(let index = 0; index < a.length; index++) {
if (a[index] % 2 === 0) {
i = index;
break;
}
}
複製代碼
ES6數組方法findIndex
實現
const a = [1,2,3];
const i = a.findIndex(value => value % 2 === 0);
複製代碼
find
for循環獲取第一個偶數
const a = [1,2,3];
let i;
for(let index = 0; index < a.length; index++) {
if (a[index] % 2 === 0) {
i = a[index];
break;
}
}
複製代碼
ES6數組方法find
實現
const a = [1,2,3];
const i = a.find(value => value % 2 === 0);
複製代碼
find
未找到偶數時,會返回undefined
以上例子只是針對一些很簡單的場景,複雜的場景就須要同窗們觸類旁通了。但願對剛入坑的同窗有所幫助。該文也是我在掘金的第一篇文章,由簡入繁,但願在新的一年裏本身能多總結多產出多分享。