Javascript ES6 - 生成数字数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39924644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 - generate an array of numbers
提问by Wasteland
Having googled for it I found two solutions:
谷歌搜索后,我找到了两个解决方案:
var data = [...Array(10).keys()];
console.log(data);
var data1 = Array(8).fill().map((_, i) => i);
console.log(data1);
data1 displays [0, 1, ..., 7] however data just displays [[object Array Iterator]] how do I actually see the numbers.
data1 显示 [0, 1, ..., 7] 但是 data 只显示 [[object Array Iterator]] 我如何实际看到数字。
I need it for some iterations over numbers (part of Euler project).
我需要它对数字进行一些迭代(欧拉项目的一部分)。
Previously I did a lot of Euler challenges in Python. Now I decided I'll revisit it and do as much as I can in JS (as much ES6 syntax as possible) to help me develop my js skills.
之前我在 Python 中做了很多 Euler 挑战。现在我决定重新审视它并尽可能多地使用 JS(尽可能多的 ES6 语法)来帮助我发展我的 js 技能。
回答by Mouad Debbar
Here is a simple solution that works in codepen:
这是一个适用于 codepen 的简单解决方案:
Array.from(Array(10).keys())
To be clear, Array.from()
and Array.keys()
require an ES6 polyfill in order to work in all browsers.
需要明确的是,Array.from()
和Array.keys()
以工作在所有的浏览器需要一个ES6填充工具。
回答by Thank you
A tour of Array.from thru practical examples
通过实际示例了解 Array.from
Array.from
also accepts a second argument which is used as a mapping function
Array.from
还接受用作映射函数的第二个参数
let out = Array.from(Array(10), (_,x) => x);
console.log(out);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This is nice to know because you might want to generate arrays that are sometimes more complex than just 0
thru N
.
很高兴知道这一点,因为您可能想要生成有时比0
thru更复杂的数组N
。
const sq = x => x * x;
let out = Array.from(Array(10), (_,x) => sq(x));
console.log(out);
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Or you can make arrays out of generators, too
或者你也可以用生成器制作数组
function* range(start, end, step) {
while (start < end) {
yield start;
start += step;
}
}
let out = Array.from(range(10,20,2));
console.log(out); // [10, 12, 14, 16, 18]
Array.from
is just massively powerful. People don't even realize its full potential yet.
Array.from
只是非常强大。人们甚至还没有意识到它的全部潜力。
const ord = x => x.charCodeAt(0);
const dec2hex = x => `0${x.toString(16)}`.substr(-2);
// common noob code
{
let input = "hello world";
let output = input.split('').map(x => dec2hex(ord(x)));
console.log(output);
// ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
}
// Array.from
{
let input = "hello world";
let output = Array.from(input, x => dec2hex(ord(x)));
console.log(output);
// ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
}
回答by Oriol
It seems the problem is that codepen precompiles your code using babel es2015-loose.
似乎问题在于 codepen 使用 babel es2015-loose 预编译您的代码。
In that mode, your
在那种模式下,你的
[...Array(10).keys()];
becomes
变成
[].concat(Array(10).keys());
And that's why you see an array containing an iterator.
这就是为什么你会看到一个包含迭代器的数组。
With es2015 mode you would get
使用 es2015 模式,你会得到
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
[].concat(_toConsumableArray(Array(10).keys()));
which would behave as desired.
这将按预期运行。
See ②ality - Babel 6: loose modefor more information about the modes.
有关模式的更多信息,请参阅②ality - Babel 6:松散模式。
回答by murrayju
All of the other answers here create a temporary intermediate array, which isn't necessary.
这里的所有其他答案都会创建一个临时的中间数组,这不是必需的。
Array.from({ length: 10 }, (_, i) => i)
This is essentially a map function where you map from array index to whatever you'd like, for any number of elements.
这本质上是一个映射函数,您可以将数组索引映射到任意数量的元素。
回答by Dwight Rodriques
Further refinement, produces an array with value starting from 1:
进一步细化,生成一个值从 1 开始的数组:
Array.from(Array(10).keys(), n => n + 1)
回答by Pranav Shukla
Here is a range
function which takes start
, end
, and a step
parameter. It returns an array starting a from start
upto (but excluding) the end
number with increments of size step
.
这里是一个range
函数,它接受start
,end
和step
参数。它返回一个数组,从start
up 到(但不包括)以end
size 为增量的数字开始step
。
const range = (start, end, step) => {
return Array.from(Array.from(Array(Math.ceil((end-start)/step)).keys()), x => start+ x*step);
}
console.log(range(1, 10, 1));
//[1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(range(0, 9, 3));
//[0, 3, 6]
console.log(range(10, 30, 5));
//[10, 15, 20, 25]
Taking a step further, if you want a range that includes the end
as well.
更进一步,如果您想要一个包含 的范围end
。
const inclusiveRange = (start, end, step) => {
return Array.from(Array.from(Array(Math.ceil((end-start+1)/step)).keys()), x => start+ x*step);
}
console.log(inclusiveRange(1, 10, 1));
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(inclusiveRange(0, 9, 3));
// [0, 3, 6, 9]
console.log(inclusiveRange(10, 30, 5));
//[10, 15, 20, 25, 30]