非标
此特征是非标准的,且不在标准轨道中。不要在面向 Web 的生产站点中使用它:它不适用于每个用户。实现之间可能存在大的不兼容性,且行为将来可能改变。

Obsolete since Gecko 58 (Firefox 58 / Thunderbird 58 / SeaMonkey 2.55)
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

Non-standard. Do not use!
The generator comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using generator .

generator comprehension syntax was a JavaScript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. However, it has been removed from the standard and the Firefox implementation. Do not use it!

句法

(for (x of iterable) x)
(for (x of iterable) if (condition) x)
(for (x of iterable) for (y of iterable) x + y)
					

描述

Inside generator comprehensions, these two kinds of components are allowed:

for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed.

A significant drawback of array comprehensions is that they cause an entire new array to be constructed in memory. When the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.

Generators enable lazy computation of sequences, with items calculated on-demand as they are needed. Generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily. You can think of them as short hand syntax for creating generators.

Suppose we have an iterator it which iterates over a large sequence of integers. We want to create a new iterator that will iterate over their doubles. An array comprehension would create a full array in memory containing the doubled values:

var doubles = [for (i in it) i * 2];
					

A generator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed:

var it2 = (for (i in it) i * 2);
console.log(it2.next()); // The first value from it, doubled
console.log(it2.next()); // The second value from it, doubled
					

When a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted:

var result = doSomething(for (i in it) i * 2);
					

The significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.

范例

Simple generator comprehensions

(for (i of [1, 2, 3]) i * i );
// generator function which yields 1, 4, and 9
[...(for (i of [1, 2, 3]) i * i )];
// [1, 4, 9]
var abc = ['A', 'B', 'C'];
(for (letters of abc) letters.toLowerCase());
// generator function which yields "a", "b", and "c"
					

Generator comprehensions with if statement

var years = [1954, 1974, 1990, 2006, 2010, 2014];
(for (year of years) if (year > 2000) year);
// generator function which yields 2006, 2010, and 2014
(for (year of years) if (year > 2000) if (year < 2010) year);
// generator function which yields 2006, the same as below:
(for (year of years) if (year > 2000 && year < 2010) year);
// generator function which yields 2006
					

Generator comprehensions compared to generator function

An easy way to understand generator comprehension syntax, is to compare it with the generator function.

Example 1: Simple generator.

var numbers = [1, 2, 3];
// Generator function
(function*() {
  for (let i of numbers) {
    yield i * i;
  }
})();
// Generator comprehension
(for (i of numbers) i * i );
// Result: both return a generator which yields [1, 4, 9]
					

Example 2: Using if in generator.

var numbers = [1, 2, 3];
// Generator function
(function*() {
  for (let i of numbers) {
    if (i < 3) {
      yield i * 1;
    }
  }
})();
// Generator comprehension
(for (i of numbers) if (i < 3) i);
// Result: both return a generator which yields [1, 2]
					

规范

Generator comprehensions were initially in the ECMAScript 2015 draft, but got removed in revision 27 (August 2014). Please see older revisions of ES2015 for specification semantics.

浏览器兼容性

Supported nowhere. Historically supported in Firefox 30 till 58.

Differences to the older JS1.7/JS1.8 comprehensions

JS1.7/JS1.8 comprehensions are removed from Gecko 46 ( bug 1220564 ).

Old comprehensions syntax (do not use anymore!):

(X for (Y in Z))
(X for each (Y in Z))
(X for (Y of Z))
				

Differences:

  • ES7 comprehensions create one scope per "for" node instead of the comprehension as a whole.
    • 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.
  • ES7 comprehensions start with "for" instead of the assignment expression.
    • Old: (i * 2 for (i of numbers))
    • New: (for (i of numbers) i * 2)
  • ES7 comprehensions can have multiple if and for components.
  • ES7 comprehensions only work with for...of and not with for...in iterations.

另请参阅

元数据

  • 最后修改:
  1. JavaScript
  2. 教程:
  3. 完全初学者
    1. JavaScript 基础
    2. JavaScript 第一步
    3. JavaScript 构建块
    4. 引入 JavaScript 对象
  4. JavaScript 指南
    1. 介绍
    2. 语法和类型
    3. 控制流程和错误处理
    4. 循环和迭代
    5. 函数
    6. 表达式和运算符
    7. 数字和日期
    8. 文本格式化
    9. 正则表达式
    10. 索引集合
    11. 键控集合
    12. Working with objects
    13. 对象模型的细节
    14. Using promises
    15. 迭代器和生成器
    16. Meta programming
    17. JavaScript 模块
  5. 中间体
    1. 引入 JavaScript 对象
    2. 客户端侧 Web API
    3. 重新介绍 JavaScript
    4. JavaScript 数据结构
    5. 相等比较和相同
    6. 闭包
  6. 高级
    1. 继承和原型链
    2. 严格模式
    3. JavaScript 类型数组
    4. 内存管理
    5. 并发模型和事件循环
  7. 参考:
  8. 内置对象
    1. AggregateError
    2. Array
    3. ArrayBuffer
    4. AsyncFunction
    5. AsyncIterator
    6. Atomics
    7. BigInt
    8. BigInt64Array
    9. BigUint64Array
    10. 布尔
    11. DataView
    12. Date
    13. Error
    14. EvalError
    15. Float32Array
    16. Float64Array
    17. Function
    18. Generator
    19. GeneratorFunction
    20. Infinity
    21. Int16Array
    22. Int32Array
    23. Int8Array
    24. InternalError
    25. Intl
    26. Iterator
    27. JSON
    28. Map
    29. Math
    30. NaN
    31. Number
    32. Object
    33. Promise
    34. Proxy
    35. RangeError
    36. ReferenceError
    37. Reflect
    38. RegExp
    39. Set
    40. SharedArrayBuffer
    41. String
    42. Symbol
    43. SyntaxError
    44. TypeError
    45. TypedArray
    46. URIError
    47. Uint16Array
    48. Uint32Array
    49. Uint8Array
    50. Uint8ClampedArray
    51. WeakMap
    52. WeakSet
    53. WebAssembly
    54. decodeURI()
    55. decodeURIComponent()
    56. encodeURI()
    57. encodeURIComponent()
    58. escape()
    59. eval()
    60. globalThis
    61. isFinite()
    62. isNaN()
    63. null
    64. parseFloat()
    65. parseInt()
    66. undefined
    67. unescape()
    68. uneval()
  9. 表达式 & 运算符
    1. 算术运算符
    2. Array comprehensions
    3. 赋值运算符
    4. Bitwise operators
    5. 逗号运算符
    6. Comparison operators
    7. 条件 (三元) 运算符
    8. Destructuring assignment
    9. Expression closures
    10. 函数表达式
    11. Generator comprehensions
    12. Grouping operator
    13. Logical operators
    14. Nullish coalescing operator
    15. 对象初始化器
    16. 运算符优先级
    17. Optional chaining
    18. Pipeline operator
    19. 特性访问器
    20. 传播句法
    21. 异步函数表达式
    22. await
    23. class expression
    24. delete operator
    25. function* 表达式
    26. in operator
    27. instanceof
    28. new operator
    29. new.target
    30. super
    31. this
    32. typeof
    33. void 运算符
    34. yield
    35. yield*
  10. 语句 & 声明
    1. async function
    2. block
    3. break
    4. class
    5. const
    6. continue
    7. debugger
    8. default
    9. do...while
    10. empty
    11. export
    12. for
    13. for await...of
    14. for each...in
    15. for...in
    16. for...of
    17. 函数声明
    18. function*
    19. if...else
    20. import
    21. import.meta
    22. label
    23. let
    24. return
    25. switch
    26. throw
    27. try...catch
    28. var
    29. while
    30. with
  11. 函数
    1. 箭头函数表达式
    2. 默认参数
    3. 方法定义
    4. 其余参数
    5. 自变量对象
    6. getter
    7. setter
    1. Class fields
    2. 构造函数
    3. extends
    4. static
  12. 错误
    1. Error: Permission denied to access property "x"
    2. InternalError: too much recursion
    3. RangeError: argument is not a valid code point
    4. RangeError: invalid array length
    5. RangeError: invalid date
    6. RangeError: precision is out of range
    7. RangeError: radix must be an integer
    8. RangeError: repeat count must be less than infinity
    9. RangeError: repeat count must be non-negative
    10. ReferenceError: "x" is not defined
    11. ReferenceError: assignment to undeclared variable "x"
    12. ReferenceError: can't access lexical declaration`X' before initialization
    13. ReferenceError: deprecated caller or arguments usage
    14. ReferenceError: invalid assignment left-hand side
    15. ReferenceError: reference to undefined property "x"
    16. SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
    17. SyntaxError: "use strict" not allowed in function with non-simple parameters
    18. SyntaxError: "x" is a reserved identifier
    19. SyntaxError: JSON.parse: bad parsing
    20. SyntaxError: Malformed formal parameter
    21. SyntaxError: Unexpected token
    22. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
    23. SyntaxError: a declaration in the head of a for-of loop can't have an initializer
    24. SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
    25. SyntaxError: for-in loop head declarations may not have initializers
    26. SyntaxError: function statement requires a name
    27. SyntaxError: identifier starts immediately after numeric literal
    28. SyntaxError: illegal character
    29. SyntaxError: invalid regular expression flag "x"
    30. SyntaxError: missing ) after argument list
    31. SyntaxError: missing ) after condition
    32. SyntaxError: missing : after property id
    33. SyntaxError: missing ; before statement
    34. SyntaxError: missing = in const declaration
    35. SyntaxError: missing ] after element list
    36. SyntaxError: missing formal parameter
    37. SyntaxError: missing name after . operator
    38. SyntaxError: missing variable name
    39. SyntaxError: missing } after function body
    40. SyntaxError: missing } after property list
    41. SyntaxError: redeclaration of formal parameter "x"
    42. SyntaxError: return not in function
    43. SyntaxError: test for equality (==) mistyped as assignment (=)?
    44. SyntaxError: unterminated string literal
    45. TypeError: "x" has no properties
    46. TypeError: "x" is (not) "y"
    47. TypeError: "x" is not a constructor
    48. TypeError: "x" is not a function
    49. TypeError: "x" is not a non-null object
    50. TypeError: "x" is read-only
    51. TypeError: 'x' is not iterable
    52. TypeError: More arguments needed
    53. TypeError: Reduce of empty array with no initial value
    54. TypeError: X.prototype.y called on incompatible type
    55. TypeError: can't access dead object
    56. TypeError: can't access property "x" of "y"
    57. TypeError: can't assign to property "x" on "y": not an object
    58. TypeError: can't define property "x": "obj" is not extensible
    59. TypeError: can't delete non-configurable array element
    60. TypeError: can't redefine non-configurable property "x"
    61. TypeError: cannot use 'in' operator to search for 'x' in 'y'
    62. TypeError: cyclic object value
    63. TypeError: invalid 'instanceof' operand 'x'
    64. TypeError: invalid Array.prototype.sort argument
    65. TypeError: invalid arguments
    66. TypeError: invalid assignment to const "x"
    67. TypeError: property "x" is non-configurable and can't be deleted
    68. TypeError: setting getter-only property "x"
    69. TypeError: variable "x" redeclares argument
    70. URIError: malformed URI sequence
    71. Warning: -file- is being assigned a //# sourceMappingURL, but already has one
    72. Warning: 08/09 is not a legal ECMA-262 octal constant
    73. Warning: Date.prototype.toLocaleFormat is deprecated
    74. Warning: JavaScript 1.6's for-each-in loops are deprecated
    75. Warning: String.x is deprecated; use String.prototype.x instead
    76. Warning: expression closures are deprecated
    77. Warning: unreachable code after return statement
  13. 杂项
    1. JavaScript 技术概述
    2. 词法语法
    3. JavaScript 数据结构
    4. Enumerability and ownership of properties
    5. Iteration protocols
    6. 严格模式
    7. 过渡到严格模式
    8. 模板文字
    9. 弃用特征