Javascript 如何在javascript中生成数字/字符序列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3751520/
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
How to generate sequence of numbers/chars in javascript?
提问by Ariya Hidayat
Is there a way to generate sequence of characters or numbers in javascript?
有没有办法在javascript中生成字符或数字序列?
For example, I want to create array that contains eight 1s. I can do it with for loop, but wondering whether there is a jQuery library or javascript function that can do it for me?
例如,我想创建包含八个 1 的数组。我可以用 for 循环来做,但想知道是否有一个 jQuery 库或 javascript 函数可以为我做这件事?
采纳答案by Nick Craver
You can make your own re-usable function I suppose, for your example:
我想您可以制作自己的可重用功能,例如:
function makeArray(count, content) {
var result = [];
if(typeof content == "function") {
for(var i = 0; i < count; i++) {
result.push(content(i));
}
} else {
for(var i = 0; i < count; i++) {
result.push(content);
}
}
return result;
}
Then you could do either of these:
然后您可以执行以下任一操作:
var myArray = makeArray(8, 1);
//or something more complex, for example:
var myArray = makeArray(8, function(i) { return i * 3; });
You can give it a try here, note the above example doesn't rely on jQuery at all so you can use it without. You just don't gain anything from the library for something like this :)
你可以在这里试一试,注意上面的例子根本不依赖于 jQuery,所以你可以不用它。您只是不会从图书馆中获得任何类似这样的东西:)
回答by Ariya Hidayat
Without a for loop, here is a solution:
没有for循环,这里有一个解决方案:
Array.apply(0, Array(8)).map(function() { return 1; })
The explanation follows.
解释如下。
Array(8)
produces a sparse array with 8 elements, all undefined
. The apply
trick will turn it into a dense array. Finally, with map
, we replace that undefined
the (same) value of 1
.
Array(8)
生成一个包含 8 个元素的稀疏数组,所有undefined
. 这个apply
技巧将把它变成一个密集的数组。最后,用map
替换undefined
的(相同)值1
。
回答by Dagg Nabbit
for (var i=8, a=[]; i--;) a.push(1);
回答by ktsiolis gmail com
Using Jquery:
使用jQuery:
$.map($(Array(8)),function(val, i) { return i; })
This returns:
这将返回:
[0, 1, 2, 3, 4, 5, 6, 7]
$.map($(Array(8)),function() { return 1; })
This returns:
这将返回:
[1, 1, 1, 1, 1, 1, 1, 1]
回答by g.sui
In case you are using newer Javascript syntax, the same can be achieved using:
如果您使用较新的 Javascript 语法,可以使用以下方法实现:
Array(8).fill(1)
The following works fine too but as Matt pointed out, the keyword 'new' is redundant.
以下也可以正常工作,但正如马特指出的那样,关键字“新”是多余的。
new Array(8).fill(1)
回答by Tom Siwik
2016 - Modern Browser functionality has arrived. No need for jquery all the time.
2016 - 现代浏览器功能已经到来。不需要一直使用 jquery。
Array.from({length: 8}, (el, index) => 1 /* or index */);
You can substitute the arrow function with a simple callback function to reach a slightly wider range of supported browsers. It's, for me at least, the easiest way to iterate over an initialized array in one step.
你可以用一个简单的回调函数代替箭头函数,以达到更广泛的支持浏览器。至少对我来说,这是一步迭代初始化数组的最简单方法。
Note: IE is not supported in this solution, but there is a polyfill for that at developer.mozilla.org/...
注意:此解决方案不支持 IE,但在developer.mozilla.org/ 上有一个 polyfill 。
回答by mendezcode
One liner:
一个班轮:
new Array(10).fill(1).map( (_, i) => i+1 )
Yields:
产量:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
回答by ceving
A sequence is a stream, which computes the value when it is needed. This requires only a bit memory but more CPU time when the values is used.
序列是一个流,它在需要时计算值。当使用这些值时,这仅需要一点内存,但需要更多的 CPU 时间。
An array is a list of precomputed values. This takes some time before the first value can be used. And it requires much memory, because all possible values of the sequence must be stored in memory. And you have to define an upper limit.
数组是预先计算好的值的列表。这需要一些时间才能使用第一个值。而且它需要很多内存,因为序列的所有可能值都必须存储在内存中。你必须定义一个上限。
This means, that in most cases it is no good idea to create an array with sequence values. Instead it is better to implement the sequence as a real sequence, which is limited just by the word length of the CPU.
这意味着,在大多数情况下,创建具有序列值的数组并不是一个好主意。相反,最好将序列实现为真正的序列,这仅受 CPU 字长的限制。
function make_sequence (value, increment)
{
if (!value) value = 0;
if (!increment) increment = function (value) { return value + 1; };
return function () {
let current = value;
value = increment (value);
return current;
};
}
i = make_sequence()
i() => 0
i() => 1
i() => 2
j = make_sequence(1, function(x) { return x * 2; })
j() => 1
j() => 2
j() => 4
j() => 8
回答by kennebec
The fastest way to define an array of 8 1s is to define it-
var A= [1, 1, 1, 1, 1, 1, 1, 1];
// You'd have to need a lot of 1s to make a dedicated function worthwhile.
// Maybe in the Matrix, when you want a lot of Smiths:
Array.repeat= function(val, len){
for(var i= len, a= []; i--; ) a[i]= val;
return a;
}
var A= Array.repeat('Smith',100)
/* returned value: (String)
Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith, Smith
*/
回答by Evan Carroll
range(start,end,step)
: With ES6 Iterators
range(start,end,step)
: 使用 ES6 迭代器
You can easily create range()
generator function which can function as an iterator. This means you don't have to pre-generate the entire array.
您可以轻松创建range()
可用作迭代器的生成器函数。这意味着您不必预先生成整个数组。
function * range ( start, end, step ) {
let state = start;
while ( state < end ) {
yield state;
state += step;
}
return;
};
Now you may want to create something that pre-generates the array from the iterator and returns a list. This is useful for functions that accept an array. For this we can use Array.from()
现在您可能想要创建一些从迭代器预先生成数组并返回列表的东西。这对于接受数组的函数很有用。为此,我们可以使用Array.from()
const generate_array = (start,end,step) => Array.from( range(start,end,step) );
Now you can generate a static array easily,
现在您可以轻松生成静态数组,
const array = generate_array(1,10,2);
But when something desires an iterator (or gives you the option to use an iterator) you can easily create one too.
但是当某些东西需要迭代器(或者让你选择使用迭代器)时,你也可以轻松地创建一个。
for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
console.log(i)
}