數(shù)組的map方法
const new_array = arr.map(callback[, thisArg]);
function callback(currentValue, index, array)原數(shù)組
arr不變,返回一個新組數(shù)callback依次作用原數(shù)組的每一個成員,生成新數(shù)組中相應(yīng)的成員。callback的參數(shù)currentValue和返回值類型不需要相同一般情況,
callback的index和array不用傳一般情況,
thisArg參數(shù)不用傳。
map全局函數(shù)
也是先判斷類型,如果是數(shù)組,直接調(diào)用
如果是對象,先拿到屬性名字的數(shù)組。
這里不能用對象的屬性名的數(shù)組的
map方法,而是應(yīng)該用reduce方法,初始值是{}
因?yàn)閙ap的結(jié)果還是一個數(shù)組,而reduce的結(jié)果才可能是一個對象。這里不能用對象的值的數(shù)組,值變換之后,要和屬性名對應(yīng)起來。根據(jù)屬性名可以找到值,但是根據(jù)值,無法找到對應(yīng)的屬性名
導(dǎo)出為函數(shù),方便使用,文件名
map_function.js
// 全局函數(shù),區(qū)別于數(shù)組的reduce()方法
module.exports = function mapFunction(callback, target) {
// 如果callback不是函數(shù),調(diào)用數(shù)組的reduce會報錯
if ('function' !== typeFunction(callback)) {
return target;
}
const type = typeFunction(target)
if (type === 'array') {
return target.map(callback);
} else if (type === 'object') {
const keys = Object.keys(target);
return keys.reduce(function (accumulator, currentValue) {
accumulator[currentValue] = callback(target[currentValue]);
return accumulator;
}, {});
} else {
return target;
}
}
// private
function typeFunction(object) {
return Object.prototype.toString.call(object).slice(8, -1).toLowerCase();
}
- 測試文件,文件名為
map_function_test.js
const mapFunction = require('./map_function.js');
const log = console.log;
// 平方根
const sqrt = Math.sqrt;
log(mapFunction('', [1, 4, 9])); // [ 1, 4, 9 ]
log(mapFunction(sqrt, [1, 4, 9])); // [ 1, 2, 3 ]
log(mapFunction(sqrt, {
one : 1,
two : 4,
three : 9
})); // { one: 1, two: 2, three: 3 }
// 雙倍
const double = function(currentValue) {
return currentValue * 2;
};
log(mapFunction('', [1, 4, 9])); // [ 1, 4, 9 ]
log(mapFunction(double, [1, 4, 9])); // [ 2, 8, 18 ]
log(mapFunction(double, {
one : 1,
two : 4,
three : 9
})); // { one: 2, two: 8, three: 18 }
// 將單詞轉(zhuǎn)換為復(fù)數(shù)形式
function fuzzyPlural(single) {
var result = single.replace(/o/g, 'e');
if( single === 'kangaroo'){
result += 'se';
}
return result;
}
var words = ["foot", "goose", "moose", "kangaroo"];
var object = {
0 : "foot",
1 : "goose",
2 : "moose",
3 : "kangaroo",
};
log(mapFunction('', words)); // [ 'foot', 'goose', 'moose', 'kangaroo' ]
log(mapFunction(fuzzyPlural, words)); // [ 'feet', 'geese', 'meese', 'kangareese' ]
log(mapFunction('', object)); // { '0': 'foot', '1': 'goose', '2': 'moose', '3': 'kangaroo' }
log(mapFunction(fuzzyPlural, object)); // { '0': 'feet', '1': 'geese', '2': 'meese', '3': 'kangareese' }