熟练 Array 方法
by yakun chen
JavaScript
var items = [{
name: '服务中',
status: 'SIGNED'
}, {
name: '开发中',
status: 'UNSIGNED'
}, {
name: '本月已动销',
status: 'BUYED'
}, {
name: '本月未动销',
status: 'UNBUYED'
}];
// Array.prototype.map 遍历时候返回一个新的数组
var demo1 = items.map(function(item, i) {
return item.title = 'title'+i;
});
//console.log(demo1);
// 遍历方法
// 1. forEach 普通遍历 回调方法参数(currentValue, index, thisArray)
// 2. map 跟进里面的 return 值返回一个新的数组,很强大
//
items.forEach(function(currentValue, index, thisArray) {
currentValue.title = 'test' + index;
})
// 返回 Boolean
// 1. every 所有的元素都满足回调判断
// 2. some
//console.log('DEBUG_INFO', items);
// 1. filter 过滤 返回 数组
// Creates a new array with all of the elements of this array for which the provided filtering function returns true.
var copyItems =
items.filter(function(currentValue, index, thisArray) {
//console.log(currentValue.status, typeof currentValue.status);
// regExp.test
// regExp.test
// regExp.test
return /BUY/.test(currentValue.status);
});
console.log('DEBUG_INFO', 'filter', copyItems);
// 2. reduce
// 返回一个计算值
var computedItems =
[1,2,3,4,5].reduce(function(previousValue, currentValue, currentIndex, array) {
//console.log(currentValue);
return previousValue + currentValue;
}, 0 /* initial value */);
console.log(computedItems);