数组方法:
- forEach: array.forEach(callback,[ thisObject])
- map: array.map(callback,[ thisObject]);
- filter: array.filter(callback,[ thisObject]);
- reduce:array.reduce(callback[, initialValue])
- forEach
/*js使用方法*/
var arr = ['独孤九剑','上官飞燕','欧阳春秋','皇甫云峰']
arr.forEach( function(element, index) {
console.log(element); // 输出值
console.log(index); // 输出索引
});
/*jQ使用方法*/
$.each(arr, function(index, value, array) {
console.log(index); // 输出索引
console.log(value); // 输出值
});
- map
var arr = [1,2,3]
arr.map(function(index, elem) {
return item*item;
})
- filter
var users = [
{name: "南派三叔", "email": "nan@email.com"},
{name: "唐家三少", "email": "tang@email.com"},
{name: "天蚕土豆", "email": "tian@email.com"}
];
var emailsZhang = users
// 获得邮件
.map(function (user) { return user.email; })
// 筛选出zhang开头的邮件
.filter(function(email) { return /^t/.test(email); });
console.log(emailsZhang.join(", "));
- reduce
// 迭代
var sum = [1, 2, 3, 4]
sum.reduce(function (previous, current, index, array) {
return previous + current;
});
console.log(sum); // 10
var matrix = [
[1, 2],
[3, 4],
[5, 6]
];
// 二维数组扁平化
var flatten = matrix.reduce(function (previous, current) {
return previous.concat(current);
});
console.log(flatten); // [1, 2, 3, 4, 5, 6]
网友评论