平常開發中,若是熟悉通常的數組處理方法,常能事半功倍,有更多時間學習其餘技術,造成正向循環。
這裏總結經常使用的js數組處理方法。html
let holidays = [1, 3, 5, 7]; getSmaller = (item) => item > 3; holidays.filter(getSmaller); // [5, 7]
let holidays = [1, 3, 5, 7]; biggerThan3 = (item) => item > 3; holidays.every(biggerThan3); // false
const peoples = [ { name: 'jane', age: 23 }, { name: 'dannel', age: 43 }, { name: 'bruce', age: 56 } ]; findJane = (item) => item.name === 'jane'; const Jane = peoples.find(findJane) // {name: "jane", age: 23}
當數組中的元素在測試條件時返回 true 時, find() 返回符合條件的元素,以後的值不會再調用執行函數。若是沒有符合條件的元素返回 undefined數組
const numbers = [1, 2, 3, 4, 5, 6]; getSum = (total, curValue) => total + curValue const sum = numbers.reduce(getSum) // 21
與reduce() 相似函數
const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b); // sum is 6 var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { return a.concat(b); }); // flattened is [4, 5, 2, 3, 0, 1]
reduce與reduceRight區別學習
var a = ['1', '2', '3', '4', '5']; var left = a.reduce((sum, cur) => sum + cur); var right = a.reduceRight((sum, cur) => sum + cur); console.log(left); // "12345" console.log(right); // "54321"
Array.sort()會將數組的數值轉化成字符串,而後根據UTF-16 code 比較大小測試
var months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // ["Dec", "Feb", "Jan", "March"] var array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // [1, 100000, 21, 30, 4]
若是想要對數組降序、升序排序,就須要變通一點。原理:code
function compare(a, b) { if (a 大於 b) { // a、b的類型能夠是任意的,比較規則本身定義 return -1; } if (a 小於 b) { return 1; } // a 等於 b return 0; }
例如,一、若是是數字數組:htm
let numbers = [2, 31, 34, 1, 9]; numbers.sort(function(a, b) { return a - b; })
使用箭頭函數,可使代碼更加簡潔:對象
let numbers = [2, 31, 34, 1, 9]; numbers.sort((a, b) => a - b)
二、數組對象排序
var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ]; // 根據value排序 items.sort(function (a, b) { return a.value - b.value; }); // 根據name排序 items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // 去除大小寫的影響 var nameB = b.name.toUpperCase(); // 去除大小寫的影響 if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; });
[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true