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

}

我不知道你想要做什么事情,但是js为客户端脚本语言,所以在安全级别上就有一定的限制。

你说将 虚拟路径 映射为 物理路径 ,

那么这里有两种情况:

1、文件为客户端文件,这个明确告诉你,做不到。

2、文件为服务器上的文件,这个你可以通过ajax机制将抽象路径交给后台代码实现即可。