[ES6] 10. Array Comprehensions
ES6 10 Array
2023-09-14 09:00:55 时间
ES6 decided that Array Comprehensions will not included in this version, ES7 will include this. Therefore, only FireFox support this, you can test it under FireFox Firebug.
Since CoffeeScrip also has array comprehension, let's go over how it looks in CoffeeScript first:
for person in people console.log(person.name) if person.age > 18
console.log "#{person.name}" for person in people when person.age > 18 // In coffeeScrip, //<expression> for <elm> in <list> when <elm> <condition>
Read More: http://www.cnblogs.com/Answer1215/p/4002666.html
Array Comprehensions:
var people = [ { firstName: "Allen", secondName: "Hook", email: "allen@abc.com" }, { firstName: "Anton", secondName: "Tee", email: "tee@abc.com" }, { firstName: "Yui", secondName: "Gegg", email: "gegg@abc.com" } ];
For example, I have a list of people, and I want to get all the emails into a spreate array:
var emails = [for(person of people) person.email]; console.log(emails);
If:
you can add if segement as well after for..of:
var emails = [for(person of people) if(person.firstName === "Yui") person.email]; console.log(emails); // ["gegg@abc.com"]
Mutli for..of:
var nums = [1, 2, 3, 4, 5]; var letters = ["a", "b", "c", "d", "e"] var battleship = [for(num of nums) for(letter of letters) num + letter] console.log(battleship);
// ["1a", "1b", "1c", "1d", "1e", "2a", "2b", "2c", "2d", "2e", "3a", "3b", "3c", "3d", "3e", "4a", "4b", "4c", "4d", "4e", "5a", "5b", "5c", "5d", "5e"]
var nums = [1, 2, 3, 4, 5]; var letters = ["a", "b", "c", "d", "e"] var battleship = [for(num of nums) [for(letter of letters) num + letter]] console.log(battleship); // [["1a", "1b", "1c", 2 more...], ["2a", "2b", "2c", 2 more...], ["3a", "3b", "3c", 2 more...], ["4a", "4b", "4c", 2 more...], ["5a", "5b", "5c", 2 more...]]
String can also be considered as an 'array':
let letter = [for (letter of 'abcde') if (/[aeiou]/.test(letter)) letter].join(''); console.log(letter); // ae
相关文章
- es6 模板字符串_json字符串转成标准格式输出
- es6 模板字符串_es6 方法模板渲染
- ES6的基础语法
- es6之数组的flat(),flatMap()「建议收藏」
- ES6数组新方法[通俗易懂]
- 理解es6中的暂时性死区
- 简单编译es6
- Vue项目中的mock.js的使用以及基本用法和ES6的新增方法
- 每天3分钟,重学ES6-ES12(三)标签模版字符串
- 每天3分钟,重学ES6-ES12(六)ES7 ES8 新增内容
- 每天3分钟,重学ES6-ES12(七)ES10 新增内容
- ES6面试点-WeakMap与Map的区别
- ES6-异步遍历器(二)
- 学会ES6模块化,看这篇就够了
- ES6中Promise简单记一下笔记
- ES6新特性梳理汇总