码修
7 天前
习惯了使用数组的迭代方法, 几乎很少用到 for 循环.
今天想要快速生成一个演示的数组, 想着能不能通过 forEach 或 map 方法实现:
- var filled = new Array(100);
- filled.map(function(val, index){
- return index+1;
- });
- // I will get an array whose size is 100 and filled by undefined not int
- console.info(filled);
失败了, 结果为:(100) [empty * 100]
虽然生成了一个 length 为 100 的数组, 但数组中全是空位, 没有值. 而 JS 中迭代方法, 是直接忽略空位, 并不会处理. 所以 map 方法之后得到一个长度为 100, 全是空位的数组.
数组迭代方法不处理空位, 但是会处理 undefined 值, 思路即是将数组中的空位转化为 undefined 值.
而 Array.from 方法会将数组的空位, 转为 undefined.
在没有 Array.from 之前, 可以使用 Array.apply(null, Array(100)) 生成长度为 100, 值为 undefined 的数组.
所以, 解决办法为:
- var filled = Array.from(Array(100), (v,k) => k+1);
- console.log(filled);
- (100) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,100]
参考资料
不使用循环, 如何创建一个长度为 100 的数组 - 凌云之翼 - 博客园 https://www.cnblogs.com/liugang-vip/p/6617988.html
- Filling an array by 1~100 without loop in JavaScript - Stack Overflow
- How to print 1 to 100 without using loop statements - Quora
- Apply and arrays: three tricks https://2ality.com/2012/07/apply-tricks.html
[译]Apply 和数组: 三个技巧 - 紫云飞 - 博客园
数组的扩展 - ECMAScript 6 入门 https://es6.ruanyifeng.com/#docs/array#Array-from
来源: http://www.mzh.ren/make-an-array-from-1-to-100-without-loop-in-javascript.html