filter函数
这是个啥?过滤器?
filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或等价于 true 的值的元素创建一个新数组。callback 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callback 测试的元素会被跳过,不会被包含在新数组中。--MDN
似懂非懂。 接下来看看例子呢? 如何用filter过滤数组中大于10的元素呢?
var words = [1, 2, 3, 4, 5, 11];
function isBigEnough(element){
return element>10;
}
const result = words.filter(isBigEnough);
console.log(result);
看起来参数是一个函数的名字。
再看一个例子,使用filter创建非0 id的json。
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' }
];
var invalidEntries = 0;
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
function filterByID(item) {
if (isNumber(item.id) && item.id !== 0) {
return true;//为什么返回的是一个布尔值
}
invalidEntries++;
return false;
}
var arrByID = arr.filter(filterByID);
console.log('Filtered Array\n', arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
console.log('Number of Invalid Entries = ', invalidEntries);
// Number of Invalid Entries = 5
如何过滤数组内容呢?
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
/**
* Array filters items based on search criteria (query)
*/
function filterItems(query) {
return fruits.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
MAP函数
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
var arr =[1,2,3,4,5]
function big(num){
return num*3
}
function test(arr){
return arr.map(big);
}
console.log(test(arr));
//[ 3, 6, 9, 12, 15 ]
但是为什么这个函数的名字叫map呢?这个有些不太懂。
reduce函数
这个函数的意思是数组通过调用reduce函数,结果返回一个汇总的值,至于要做什么,这个需要自己定义函数实现。 下面说几个例子:
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// 和为 6
求和。accumulator是一个累加器。
第二个例子
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
return accumulator + currentValue.x;
},initialValue)
console.log(sum) // logs 6
求对象的和。
第三个例子:如何将二维数组转化为一维数组。
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 }
to be honest,没看明白第三个例子,待有时间再看看。 未完待续..