js数组的map方法

JavaScript010

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

}

一般的做法是将map对象转成json在jsp页面中输出,js直接得到的就是json对象,便利json使用for循环即可

for(k in json){

alert(k + "=" + json[k])

}

不可以,在应用dwr的时候可以是dwr有个转换机制让java类对象和js类对象能够互相转换,这样就能在使用dwr的时候可以把action里的map作为js函数的参数,直接把Java对象传给js是不行的!建议还是用dwr来实现吧!