【JS新手向】對for說byebye

前言

新手或從其餘語言轉前端的同窗剛接觸js時,涉及到的數組循環通常都是for、while,以for居多。前端

內容

forEachmap

好比輸入某個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新增的數組方法forEachmap也能夠更優雅的實現測試

(返回新數組)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);
複製代碼

someevery

或許有人會說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新增的數組方法someevery均可以實現相似的效果。回調函數

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);
複製代碼

reducereduceRight

某些場景下可能須要對數組的每一項都進行某種操做。好比獲取數組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

結尾

以上例子只是針對一些很簡單的場景,複雜的場景就須要同窗們觸類旁通了。但願對剛入坑的同窗有所幫助。該文也是我在掘金的第一篇文章,由簡入繁,但願在新的一年裏本身能多總結多產出多分享。

Array | MDN

相關文章
相關標籤/搜索