_.map(list, iteratee, [context])
对集合的每个成员依次进行某种操作,将返回的值依次存入一个新的数组。接收3个参数。list可理解为数据源iteratee迭代器可理解为回调方法;context执行上下文。
var result;
//操作数组
result = _.map([1, 2, 3], function (element, index, list) {
return element + 1;
});
console.log(result) //=> [2, 3, 4]
//操作对象
result = _.map({one: '一', two: '二', three: '三'}, function(value, key, list){
return value + 1;
});
console.log(result) //=> ["一1", "二1", "三1"]
//操作字符串
result = _.map('123', function(element, index, list){
return element + 1;
});
console.log(result) //=> ["11", "21", "31"]
//操作arguments
function abc(){
result = _.map(arguments, function(element, index, list){
return element + 1;
});
console.log(result); //=> [2, 3, 4]
}
abc(1, 2, 3);
var result;
//数组的情况
result = _.map([1, 2, 3], function (element, index, list) {
console.log(element, index, list);
//=> 1 0 [1, 2, 3]
//=> 2 1 [1, 2, 3]
//=> 3 2 [1, 2, 3]
});
//对象的情况
result = _.map({one: '一', two: '二', three: '三'}, function(value, key, list){
console.log(value, key, list);
//=> 一 one Object {one: "一", two: "二", three: "三"}
//=> 二 two Object {one: "一", two: "二", three: "三"}
//=> 三 three Object {one: "一", two: "二", three: "三"}
});
var arr1 = _.map([1, 2, 3], function (element, index, list) {
element + 1;
});
var arr2 = _.map([1, 2, 3], function (element, index, list) {
return element + 1;
});
console.log(arr1); //=> [undefined, undefined, undefined]
console.log(arr2); //=> [2, 3, 4]
var result = _.map([1, 2, 3], function (element, index, list) {
return element + this.no; //this为{no : 10}
}, {no : 10});
console.log(result);//=> [11, 12, 13]
var list = [1, 2, 3];
var result = _.map(list, function(element, index, list){
return element + 1;
});
console.log(list); //=> [1, 2, 3]
console.log(result); //=> [2, 3, 4]
var result = _.collect([1, 2, 3], function(element, index, list){
return element + 1;
});
console.log(result); //=> [2, 3, 4]
var arr1 = _.map(null, function (element, index, list) {
console.log(element); //不执行
});
var arr2 = _.map(undefined, function (element, index, list) {
console.log(element); //不执行
});
var arr3 = _.map(123, function (element, index, list) {
console.log(element); //不执行
});
var arr4 = _.map(new Date(), function (element, index, list) {
console.log(element); //不执行
});
console.log(arr1); //=> []
console.log(arr2); //=> []
console.log(arr3); //=> []
console.log(arr4); //=> []
var result = _.map([1, -2, -3], Math.abs);
console.log(result); //=> [1, 2, 3]
var result = _.map([1, -2, -3], console.log.bind(console));
//=> 1 0 [1, -2, -3]
//=> -2 1 [1, -2, -3]
//=> -3 2 [1, -2, -3]
我在gitbook地址:https://www.gitbook.com/book/niec-fe/underscorejs/details