如何在javascript中生成数字/字符序列? [英] How to generate sequence of numbers/chars in javascript?
问题描述
有没有办法在javascript中生成字符或数字序列?
Is there a way to generate sequence of characters or numbers in javascript?
例如,我想创建包含8个1的数组。我可以用for循环来做,但想知道是否有可以为我做的jQuery库或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?
推荐答案
对于您的示例,您可以创建自己的可重用函数:
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; });
你可以在这里尝试一下,注意上面的例子根本不依赖于jQuery,所以你可以不用它。你只是没有从图书馆获得任何东西:)
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 :)
这篇关于如何在javascript中生成数字/字符序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!