前段時間在面試的過程中被問到for in 和 for of 的區別,當時只記得for in 遍時取得值的key和index,for of 遍時取得值的value,面試結束回來就認真研究了一下異同,順帶學習了javaScript中遍歷的其他方法,在講for in 和 for of 的區別之前先跟大家說說javaScript中其他的方法。在Javascript中遍歷數組的方法通常使用的是for i 循環,但ES5增加了forEach方法,同時ES5具有遍歷數組的方法還有map、filter、some、every、reduce、reduceRight等,只不過他們的返回結果不同;但是使用forEach遍歷數組的時候,break不能中斷循環,return不能返回到外層函數。
let arr = ['d', 's', 'r', 'c']; arr.forEach(item => { if (item === 's') break; console.log(item); })
使用break就會報錯,非法語句。
一、map
map()
方法定義在JavaScript的Array
中,它返回一個新的數組,數組中的元素為原始數組調用函數處理后的值。
let arr = ['d', 's', 'r', 'c']; let arr2 = arr.map(item => item === 's') console.log(arr2);
結果:
map會對數組的每一項進行處理,返回新數組,返回的新數組包含對之前每一項處理結果;
二、filter
filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
let arr = ['d', 's', 'r', 'c']; let arr2 = arr.filter(item => item === 's') console.log(arr2);
結果:
filter只會把符合條件的數值返回,形成一個新數組;
三、some
some() 方法用於檢測數組中的元素是否滿足指定條件(函數提供)。some() 方法會依次執行數組的每個元素:如果有一個元素滿足條件,則表達式返回true , 剩余的元素不會再執行檢測。如果沒有滿足條件的元素,則返回false。
let arr = ['d', 's', 'r', 'c']; let arr2 = arr.some(item => item === 's') console.log(arr2);
結果:
some()會一直運行直到回調函數返回true;
四、every
every() 方法用於檢測數組所有元素是否都符合指定條件(通過函數提供)。every() 方法使用指定函數檢測數組中的所有元素:如果數組中檢測到有一個元素不滿足,則整個表達式返回 false ,且剩余的元素不會再進行檢測。如果所有元素都滿足條件,則返回 true。
let arr = ['d', 's', 'r', 'c']; let arr2 = arr.every(item => item === 's') console.log(arr2);
結果:
every()會一直運行直到回調函數返回false;
五、reduce
educe() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。reduce() 可以作為一個高階函數,用於函數的 compose。
let arr = ['d', 's', 'r', 'c']; let arr2 = arr.reduce((total, item) => { return total + item }, '') console.log(arr2);
結果:
因為是字符串,reduce就直接拼接了;
六、reduceRight
reduceRight() 方法的功能和 reduce()功能是一樣的,不同的是 reduceRight() 從數組的末尾向前將數組中的數組項做累加。
七、for in 和for of的遍歷異同
在講解完javaScript中其他幾種遍歷數組的方法后,我們來看一下for in 和for of的遍歷異同
for in 循環闊以用來遍歷對象的可枚舉屬性列表(包括[[Prototype]]鏈)。使用for in遍歷對象無法直接獲取到值,但是for of能取到值(前提對象本身定義了迭代器)
console.log('for...in'); let arr = ['d', 's', 'r', 'c']; for (const key in arr) { if (arr.hasOwnProperty(key)) { console.log(key); } } console.log('for...of'); for (const iterator of arr) { console.log(iterator); }
結果:
簡單總結就是,for in遍歷的是數組的索引(即鍵名),而for of遍歷的是數組元素值。
for-in總是得到對象的key或數組、字符串的下標。
for-of總是得到對象的value或數組、字符串的值,另外還可以用於遍歷Map和Set。