很多時候,我們在操作數組的時候往往就是一個for迴圈乾到底,對數組提供的其它方法視而不見。看完本文,希望你可以換種思路處理數組,然後可以寫出更加漂亮、簡潔、函數式的代碼。 reduce 數組裡所有值的和 將二維數組轉化為一維數組 計算數組中每個元素出現的次數 使用擴展運算符和initialValue ...
很多時候,我們在操作數組的時候往往就是一個for迴圈乾到底,對數組提供的其它方法視而不見。看完本文,希望你可以換種思路處理數組,然後可以寫出更加漂亮、簡潔、函數式的代碼。
reduce
數組裡所有值的和
var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
}, 0);
// sum is 6
將二維數組轉化為一維數組
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function (a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]
計算數組中每個元素出現的次數
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
使用擴展運算符和initialValue綁定包含在對象數組中的數組
// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function (prev, curr) {
return [...prev, ...curr.books];
}, ['Alphabet']);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
數組去重
var arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
var result = arr.sort().reduce(
function (init, current) {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
},
[]
);
console.log(result); //[1,2,3,4,5]
數組變整數
var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
return x * 10 + y;
}); // 13579
map
求數組中每個元素的平方根
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值為[1, 2, 3], numbers的值仍為[1, 4, 9]
格式化數組中的對象
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(function (obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// reformattedArray 數組為: [{1: 10}, {2: 20}, {3: 30}],
// kvArray 數組未被修改:
// [{key: 1, value: 10},
// {key: 2, value: 20},
// {key: 3, value: 30}]
用一個僅有一個參數的函數來mapping一個數字數組
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles數組的值為: [2, 8, 18]
// numbers數組未被修改: [1, 4, 9]
反轉字元串
var str = '12345';
Array.prototype.map.call(str, function(x) {
return x;
}).reverse().join('');
// 輸出: '54321'
// Bonus: use '===' to test if original string was a palindrome
every
檢測所有數組元素的大小
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
filter
篩選排除掉所有的小值
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
find
用對象的屬性查找數組裡的對象
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
尋找數組中的質數
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
some
測試數組元素的值
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true
sort
升序排序
var list = [1, 3, 7, 6];
list.sort(function(a, b) {
return a-b;
});
降序排序
var list = [1, 3, 7, 6];
list.sort(function(a, b) {
return b-a;
});
使用映射改善排序
// 需要被排序的數組
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
// 對需要排序的數字和位置的臨時存儲
var mapped = list.map(function (el, i) {
return {index: i, value: el.toLowerCase()};
})
// 按照多個值排序數組
mapped.sort(function (a, b) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});
// 根據索引得到排序的結果
var result = mapped.map(function (el) {
return list[el.index];
});