# [译]JavaScript中的稀疏数组与密集数组

## 1.稀疏数组

> var a = new Array(3);
> a
[ , ,  ]
> a.length
3
> a[0]
undefined

> a.forEach(function (x, i) { console.log(i+". "+x) });

> a.map(function (x, i) { return i })
[ , ,  ]

>var arr = [];
>arr[0] = 0;
>arr[100] = 100

>a.forEach(function (x, i) { console.log(i+". "+x) });
0. 0
100. 100

## 2.密集数组

Brandon Benvie 最近在es-discuss邮件讨论组中提到了一个创建密集数组的技巧:

> var a = Array.apply(null, Array(3));
> a
[ undefined, undefined, undefined ]

Array(undefined, undefined, undefined)

> a.length
3
> a[0]
undefined

> a.forEach(function (x, i) { console.log(i+". "+x) });
0. undefined
1. undefined
2. undefined

> a.map(function (x, i) { return i })
[ 0, 1, 2 ]

## 3.另一个技巧

> Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number))
[ 0, 1, 2 ]

Array.apply(null, Array(3)).map(
function (x,i,...) { return Number.call(x,i,...) })

Array.apply(null, Array(3)).map(function (x,i) { return i })

Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number))//等同于Array.apply(null, Array(3)).map(Function.prototype.call,Number)

var a = ["aaa  ", "  bbb", "  ccc  "]a.map(function(x) { return x.trim(); });               // ['aaa', 'bbb', 'ccc']a.map(Function.prototype.call, String.prototype.trim); // ['aaa', 'bbb', 'ccc']

## 4.实际用途?

> _.range(3)
[ 0, 1, 2 ]

> _.range(3).map(function () { return "a" })
[ 'a', 'a', 'a' ]

## 5.相关文章

posted @ 2012-09-16 15:08 紫云飞 阅读(...) 评论(...) 编辑 收藏