# 数组推导式

## 语法

```[for (x of iterable) x]
[for (x of iterable) if (condition) x]
[for (x of iterable) for (y of iterable) x + y]
```

## 示例

### 基本的数组推导式写法

```[for (i of [ 1, 2, 3 ]) i*i ];
// [ 1, 4, 9 ]

var abc = [ "A", "B", "C" ];
[for (letters of abc) letters.toLowerCase()];
// [ "a", "b", "c" ]```

### 带有 if 语句的数组推导式

```var years = [ 1954, 1974, 1990, 2006, 2010, 2014 ];

[for (year of years) if (year > 2000) year];
// [ 2006, 2010, 2014 ]

[for (year of years) if (year > 2000) if(year < 2010) year];
// [ 2006], 和下面的写法等效：

[for (year of years) if (year > 2000 && year < 2010) year];
// [ 2006]
```

### 用数组推导式比用数组的 `map`、`filter` 方法更简洁

```var numbers = [ 1, 2, 3 ];

numbers.map(function (i) { return i * i });
[for (i of numbers) i*i ];
// 返回值都是 [ 1, 4, 9 ]

numbers.filter(function (i) { return i < 3 });
[for (i of numbers) if (i < 3) i];
// 返回值都是 [ 1, 2 ]
```

### 带有两个数组的数组推导式

```var numbers = [ 1, 2, 3 ];
var letters = [ "a", "b", "c" ];

var cross = [for (i of numbers) for (j of letters) i+j];
// [ "1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c" ]

var grid = [for (i of numbers) [for (j of letters) i+j]];
// [
//  ["1a", "1b", "1c"],
//  ["2a", "2b", "2c"],
//  ["3a", "3b", "3c"]
// ]

[for (i of numbers) if (i > 1) for (j of letters) if(j > "a") i+j]
// ["2b", "2c", "3b", "3c"]，和下面的写法等效：

[for (i of numbers) for (j of letters) if (i > 1) if(j > "a") i+j]
// ["2b", "2c", "3b", "3c"]

[for (i of numbers) if (i > 1) [for (j of letters) if(j > "a") i+j]]
// [["2b", "2c"], ["3b", "3c"]]，和下面的写法不等效：

[for (i of numbers) [for (j of letters) if (i > 1) if(j > "a") i+j]]
// [[], ["2b", "2c"], ["3b", "3c"]]
```

## 浏览器兼容性

No compatibility data found. Please contribute data for "javascript.operators.array_comprehensions" (depth: 1) to the MDN compatibility data repository.

## 同旧版的JS1.7/JS1.8数组推导的不同之处

JS1.7/JS1.8数组推导 在Gecko的46版本中已经被移除了 (bug 1220564).

```[X for (Y in Z)]
[X for each (Y in Z)]
[X for (Y of Z)]
```

• ESNext数组推导为每个"for"创建了一个作用域而取代了整个作用域.
• Old: `[()=>x for (x of [0, 1, 2])][1]() // 2`
• New: `[for (x of [0, 1, 2]) ()=>x][1]() // 1, each iteration creates a fresh binding for x. `
• ESNext 同"for"进行赋值而取代了旧的赋值表达式.
• Old: `[i * 2 for (i of numbers)]`
• New: `[for (i of numbers) i * 2]`
• ESNext数组推导可由多个if和for组成
• ESNext数组推导只和`for...of`迭代才有效，而不会同 `for...in` 迭代.