1.map()
对数组中每一个元素都运行函数, 返回由每次函数执行的结果组成的数组。果你想对数据里的每一个元素进行处理,可以采用forEach来替换 for循环,和forEach不同的是,它最终会返回一个新的数组,数组的元素是每次处理先前数组中元素返回的结果。
var arr3 = [1,2,9,5,4];
//数组中每个元素都要翻10倍
var arr4 = arr3.map(function(ele,index,arr2){
return ele*10;
});
console.log(arr4.toString());//10,20,90,50,40
2.reduce()
对数组中的所有元素调用指定的回调函数。 该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。
function appendCurrent(previousValue, currentValue){
return previousValue + "::" + currentValue;
}
var elements = ["abc","def",123,456];
var result = elements.reduce(appendCurrent);
document.write(result);
//output: abc::def::123::456