js数组的map方法

JavaScript05

js数组的map方法,第1张

js数组的map方法

这里的map不是“地图”的意思,而是指“映射”。

[].map() 基本用法跟forEach方法类似

array.map(callback,[ thisObject])

callback的参数也类似:

[].map(function(value, index, array) {

// ...

})

map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组。下面这个例子是数值项求平方:

var data = [1, 2, 3, 4]

var arrayOfSquares = data.map(function (item) {

return item * item

})

alert(arrayOfSquares) // [1, 4, 9, 16]

callback需要有return值,如果没有,就像下面这样:

var data = [1, 2, 3, 4]

var arrayOfSquares = data.map(function() {})

arrayOfSquares.forEach(console.log)

结果可以看到,数组所有项都被映射成了undefined:

在实际使用的时候,我们可以利用map方法方便获得对象数组中的特定属性值们。例如下面这个例子(之后的兼容demo也是该例子):

var users = [

{name: "张含韵", "email": "[email protected]"},

{name: "江一燕",   "email": "[email protected]"},

{name: "李小璐",  "email": "[email protected]"}

]

var emails = users.map(function (user) { return user.email})

console.log(emails.join(", "))// [email protected], [email protected], [email protected]

Array.prototype扩展可以让IE6-IE8浏览器也支持map方法:

if (typeof Array.prototype.map != "function") {

Array.prototype.map = function (fn, context) {

var arr = []

if (typeof fn === "function") {

for (var k = 0, length = this.lengthk <lengthk++) {

arr.push(fn.call(context, this[k], k, this))

}

}

return arr

}

forEach: 对数组中每一个元素都运行函数,该方法没有返回值。如果你想对数据里的每一个元素进行处理,可以采用forEach来替换 for循环

map:对数组中每一个元素都运行函数, 返回由每次函数执行的结果组成的数组。果你想对数据里的每一个元素进行处理,可以采用forEach来替换 for循环,和forEach不同的是,它最终会返回一个新的数组,数组的元素是每次处理先前数组中元素返回的结果

reduce: 对数组中的所有元素调用指定的回调函数。 该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。

还是看例子来理解吧:

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 

 

arr3.forEach(function(ele,index,arr){  

    console.log("模拟插入元素到数据库:"+ele)  

})

打印结果:  

模拟插入元素到数据库:1  

模拟插入元素到数据库:2

模拟插入元素到数据库:9 

模拟插入元素到数据库:5

模拟插入元素到数据库:4

reduce的测试例子:

// Define the callback function.

function appendCurrent (previousValue, currentValue) {

    return previousValue + "::" + currentValue

    }

 

// Create an array.

var elements = ["abc", "def", 123, 456]

 

// Call the reduce method, which calls the callback function

// for each array element.

var result = elements.reduce(appendCurrent)

 

document.write(result)

 

// Output:

//  abc::def::123::456

定义和用法:

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值

map() 方法按照原始数组元素顺序依次处理元素。

注意: map() 不会对空数组进行检测。

注意: map() 不会改变原始数组。

实例:

返回一个数组,数组中元素为原始数组的平方根:

var numbers = [4, 9, 16, 25]

function myFunction() {

    x = document.getElementById("demo")

    x.innerHTML = numbers.map(Math.sqrt)

}

输出结果为:

2,3,4,5