Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Array comprehensions - JavaScript | MDN Skip to main content Select language Skip to search MDN Web Docs Technologies HTML CSS JavaScript Graphics HTTP APIs / DOM Browser Extensions MathML References & Guides Learn web development Tutorials References Developer Guides Accessibility Game development ...more docs Feedback Get Firefox help Get web development help Join the MDN community Report a content problem Report a bug Sign in Github Search Search Close search Array comprehensions Languages Deutsch (de) Español (es) Français (fr) 日本語 (ja) 한국어 (ko) Português (do Brasil) (pt-BR) Русский (ru) 中文 (简体) (zh-CN) Add a translation Edit Advanced Advanced History Print this article Jump to: Syntax Description Examples Specifications Browser compatibility Differences to the older JS1.7/JS1.8 comprehensions See also Non-standard. Do not use! The array comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using Array.prototype.map, Array.prototype.filter, arrow functions, and spread syntax. 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. The array comprehension syntax was a JavaScript expression which allowed you to quickly assemble a new array based on an existing one. However, it has been removed from the standard and the Firefox implementation. Do not use it! Syntax [for (x of iterable) x] [for (x of iterable) if (condition) x] [for (x of iterable) for (y of iterable) x + y] Description Inside array comprehensions, these two kinds of components are allowed: for...of and if The for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed. Array comprehension was previously proposed to be standardized in ECMAScript 2016, it provide a useful shortcut for constructing a new array based on the contents of another. Comprehensions can often be used in place of calls to map() and filter(), or as a way of combining the two. The following comprehension takes an array of numbers and creates a new array of the double of each of those numbers. This is equivalent to the following map() operation: Comprehensions can also be used to select items that match a particular expression. Here is a comprehension which selects only even numbers: filter() can be used for the same purpose: map() and filter() style operations can be combined into a single array comprehension. Here is one that filters just the even numbers, then creates an array containing their doubles: The square brackets of an array comprehension introduce an implicit block for scoping purposes. New variables (such as i in the example) are treated as if they had been declared using let. This means that they will not be available outside of the comprehension. The input to an array comprehension does not itself need to be an array; iterators and generators can also be used. Even strings may be used as input; to achieve the filter and map actions (under Array-like objects) above: Again, the input form is not preserved, so we have to use join() to revert back to a string. Examples Simple array comprehensions [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"] Array comprehensions with if statement Array comprehensions compared to map and filter An easy way to understand array comprehension syntax, is to compare it with the Array map and filter methods: Array comprehensions with two arrays Using two for-of iterations to work with two arrays: Specifications Was initially in the ECMAScript 2015 draft, but got removed in revision 27 (August 2014). Please see older revisions of ES2015 for specification semantics. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Update compatibility data on GitHub Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js Array comprehensions DeprecatedNon-standard Chrome No support No Edge No support No Firefox No support 30 — 58 IE No support No Opera No support No Safari No support No WebView Android No support No Chrome Android No support No Firefox Android No support 30 — 58 Opera Android No support No Safari iOS No support No Samsung Internet Android No support No nodejs No support No Legend No support   No support Non-standard. Expect poor cross-browser support. Non-standard. Expect poor cross-browser support. Deprecated. Not for use in new websites. Deprecated. Not for use in new websites. Differences to the older JS1.7/JS1.8 comprehensions JS1.7/JS1.8 comprehensions are removed from Gecko starting with version 46 (bug 1220564). Old comprehensions syntax (do not use anymore!): Differences: ESNext 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. ESNext comprehensions start with "for" instead of the assignment expression. Old: [i * 2 for (i of numbers)] New: [for (i of numbers) i * 2] ESNext comprehensions can have multiple if and for components. ESNext comprehensions only work with for...of and not with for...in iterations. See Bug 1220564, comment 42 for suggestions on updating code. See also for...of Generator comprehensions Document Tags and Contributors Tags:  JavaScript Non-standard Obsolete Operator Reference Contributors to this page: mdnwebdocs-bot, ExE-Boss, fscholz, shoelaces, nmve, spicyj, kdex, isonic, tschneidereit, arai, TimothyGu, so_matt_basta, jwhitlock, P0lip, cirocosta, ziyunfei Last updated by: mdnwebdocs-bot, Mar 18, 2019, 4:30:56 PM Web technology for developers JavaScript JavaScript reference Expressions and operators Array comprehensions Related Topics JavaScript Tutorials: Complete beginners JavaScript basics JavaScript first steps JavaScript building blocks Introducing JavaScript objects JavaScript Guide Introduction Grammar and types Control flow and error handling Loops and iteration Functions Expressions and operators Numbers and dates Text formatting Regular expressions Indexed collections Keyed collections Working with objects Details of the object model Using promises Iterators and generators Meta programming JavaScript modules Intermediate Introducing JavaScript objects Client-side web APIs A re-introduction to JavaScript JavaScript data structures Equality comparisons and sameness Closures Advanced Inheritance and the prototype chain Strict mode JavaScript typed arrays Memory Management Concurrency model and Event Loop References: Built-in objects Array ArrayBuffer AsyncFunction Atomics BigInt BigInt64Array BigUint64Array Boolean DataView Date Error EvalError Float32Array Float64Array Function Generator GeneratorFunction Infinity Int16Array Int32Array Int8Array InternalError Intl Intl.Collator Intl.DateTimeFormat Intl.ListFormat Intl.Locale Intl.NumberFormat Intl.PluralRules Intl.RelativeTimeFormat JSON Map Math NaN Number Object Promise Proxy RangeError ReferenceError Reflect RegExp Set SharedArrayBuffer String Symbol SyntaxError TypeError TypedArray URIError Uint16Array Uint32Array Uint8Array Uint8ClampedArray WeakMap WeakSet WebAssembly decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() globalThis isFinite() isNaN() null parseFloat() parseInt() undefined unescape() uneval() Expressions & operators Arithmetic operators Array comprehensions Assignment operators Bitwise operators Comma operator Comparison operators Conditional (ternary) operator Destructuring assignment Expression closures Generator comprehensions Grouping operator Legacy generator function expression Logical operators Object initializer Operator precedence Optional chaining Pipeline operator Property accessors Spread syntax async function expression await class expression delete operator function expression function* expression in operator instanceof new operator new.target super this typeof void operator yield yield* Statements & declarations Legacy generator function async function block break class const continue debugger default do...while empty export for for await...of for each...in for...in for...of function declaration function* if...else import import.meta label let return switch throw try...catch var while with Functions Arrow functions Default parameters Method definitions Rest parameters The arguments object getter setter Classes constructor extends static Errors Error: Permission denied to access property "x" InternalError: too much recursion RangeError: argument is not a valid code point RangeError: invalid array length RangeError: invalid date RangeError: precision is out of range RangeError: radix must be an integer RangeError: repeat count must be less than infinity RangeError: repeat count must be non-negative ReferenceError: "x" is not defined ReferenceError: assignment to undeclared variable "x" ReferenceError: can't access lexical declaration`X' before initialization ReferenceError: deprecated caller or arguments usage ReferenceError: invalid assignment left-hand side ReferenceError: reference to undefined property "x" SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated SyntaxError: "use strict" not allowed in function with non-simple parameters SyntaxError: "x" is a reserved identifier SyntaxError: JSON.parse: bad parsing SyntaxError: Malformed formal parameter SyntaxError: Unexpected token SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead SyntaxError: a declaration in the head of a for-of loop can't have an initializer SyntaxError: applying the 'delete' operator to an unqualified name is deprecated SyntaxError: for-in loop head declarations may not have initializers SyntaxError: function statement requires a name SyntaxError: identifier starts immediately after numeric literal SyntaxError: illegal character SyntaxError: invalid regular expression flag "x" SyntaxError: missing ) after argument list SyntaxError: missing ) after condition SyntaxError: missing : after property id SyntaxError: missing ; before statement SyntaxError: missing = in const declaration SyntaxError: missing ] after element list SyntaxError: missing formal parameter SyntaxError: missing name after . operator SyntaxError: missing variable name SyntaxError: missing } after function body SyntaxError: missing } after property list SyntaxError: redeclaration of formal parameter "x" SyntaxError: return not in function SyntaxError: test for equality (==) mistyped as assignment (=)? SyntaxError: unterminated string literal TypeError: "x" has no properties TypeError: "x" is (not) "y" TypeError: "x" is not a constructor TypeError: "x" is not a function TypeError: "x" is not a non-null object TypeError: "x" is read-only TypeError: 'x' is not iterable TypeError: More arguments needed TypeError: Reduce of empty array with no initial value TypeError: X.prototype.y called on incompatible type TypeError: can't access dead object TypeError: can't access property "x" of "y" TypeError: can't assign to property "x" on "y": not an object TypeError: can't define property "x": "obj" is not extensible TypeError: can't delete non-configurable array element TypeError: can't redefine non-configurable property "x" TypeError: cannot use 'in' operator to search for 'x' in 'y' TypeError: cyclic object value TypeError: invalid 'instanceof' operand 'x' TypeError: invalid Array.prototype.sort argument TypeError: invalid arguments TypeError: invalid assignment to const "x" TypeError: property "x" is non-configurable and can't be deleted TypeError: setting getter-only property "x" TypeError: variable "x" redeclares argument URIError: malformed URI sequence Warning: -file- is being assigned a //# sourceMappingURL, but already has one Warning: 08/09 is not a legal ECMA-262 octal constant Warning: Date.prototype.toLocaleFormat is deprecated Warning: JavaScript 1.6's for-each-in loops are deprecated Warning: String.x is deprecated; use String.prototype.x instead Warning: expression closures are deprecated Warning: unreachable code after return statement Misc JavaScript technologies overview Lexical grammar JavaScript data structures Enumerability and ownership of properties Iteration protocols Strict mode Transitioning to strict mode Template literals Deprecated features New in JavaScript ECMAScript 2015 support in Mozilla ECMAScript 5 support in Mozilla Firefox JavaScript changelog New in JavaScript 1.1 New in JavaScript 1.2 New in JavaScript 1.3 New in JavaScript 1.4 New in JavaScript 1.5 New in JavaScript 1.6 New in JavaScript 1.7 New in JavaScript 1.8 New in JavaScript 1.8.1 New in JavaScript 1.8.5 Documentation: Useful lists All pages index Methods index Properties index Pages tagged "JavaScript" Contribute JavaScript doc status The MDN project Learn the best of web development Get the latest and greatest from MDN delivered straight to your inbox. E-mail I'm okay with Mozilla handling my info as explained in this Privacy Policy. Sign up now Thanks! Please check your inbox to confirm your subscription. If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us. Hide Newsletter Sign-up MDN Survey Help us understand the top 10 needs of Web developers and designers. Take the survey Minimize banner Close banner MDN Web Docs MDN Web Technologies Learn Web Development About MDN Feedback Twitter GitHub Mozilla Mozilla About Contact Us Firefox Twitter Instagram Other languages: English (US) (en-US) Deutsch (de) Español (es) Français (fr) 日本語 (ja) 한국어 (ko) Português (do Brasil) (pt-BR) Русский (ru) 中文 (简体) (zh-CN) Go Terms Privacy Cookies © 2005-2019 Mozilla and individual contributors. Content is available under these licenses.