如何在javascript中生成数字/字符序列?

时间:2010-09-20 12:36:33

标签: javascript jquery

有没有办法在javascript中生成字符或数字序列?

例如,我想创建包含8个1的数组。我可以用for循环来做,但想知道是否有一个jQuery库或javascript函数可以为我做这个?

20 个答案:

答案 0 :(得分:38)

没有for循环,这是一个解决方案:

Array.apply(0, Array(8)).map(function() { return 1; })

解释如下。

Array(8)生成一个包含8个元素的稀疏数组,全部为undefinedapply技巧会将其变成密集阵列。最后,使用map,我们将undefined 1的{​​{1}}替换为{{1}}。

答案 1 :(得分:16)

for (var i=8, a=[]; i--;) a.push(1);

答案 2 :(得分:14)

我想你可以制作自己的可重复使用的功能,例如:

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;
}

然后你可以做以下任何一种:

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,请注意上面的示例根本不依赖于jQuery,因此您可以不使用它。你只是没有从图书馆获得任何东西:)

答案 3 :(得分:10)

使用Jquery:


$.map($(Array(8)),function(val, i) { return i; })

返回:

[0, 1, 2, 3, 4, 5, 6, 7]

$.map($(Array(8)),function() { return 1; })

返回:

[1, 1, 1, 1, 1, 1, 1, 1]

答案 4 :(得分:10)

如果您使用较新的Javascript语法,可以使用以下方法实现相同的目的:

Array(8).fill(1)

以下工作也很好,但正如马特指出的那样,关键字“新”&#39;是多余的。

new Array(8).fill(1)

答案 5 :(得分:4)

2016 - 现代浏览器功能已经到来。不需要jquery。

Array.from({length: 8}, (el, index) => 1 /* or index */);

您可以使用简单的回调函数替换箭头功能,以获得更广泛的支持浏览器范围。至少对我来说,这是在一步中迭代初始化数组的最简单方法。

注意:此解决方案不支持IE,但在developer.mozilla.org/...

处有一个polyfill

答案 6 :(得分:3)

序列是一个流,它在需要时计算值。这只需要一点内存,但在使用这些值时需要更多的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

答案 7 :(得分:1)

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
*/

答案 8 :(得分:0)

这是迄今为止最简单的一个

const sequence = [...Array(10).keys()]
console.log(sequence)

Output : [0,1,2,3,4,5,6,7,8,9]

答案 9 :(得分:0)

Javascript ES6 运行 :)

Array(8).fill(1)

console.log(Array(8).fill(1))

答案 10 :(得分:0)

如果要产生一个相等的数字序列,这是一个很好的功能(解决方案类似于其他答案):

seq = (n, value) => Array(n).fill(value)

如果您要生成一个从0开始的连续数字序列,这是一个不错的选择:

seq = n => n<1 ? [] : [0, ...seq(n-1).map(v => v+1)]

它可以轻松扩展为不同的起始值和增量:

seq = (n, start=0, inc=1) => n<1 ? [] : [start, ...seq(n-1, start, inc).map(v => v+inc)]

答案 11 :(得分:0)

这是一个不错的选择

var result = [];
for (var i = 1; i != 4; ++i) result.push(i)

在此处查看更多选项https://ariya.io/2013/07/sequences-using-javascript-array

答案 12 :(得分:0)

var GetAutoNumber = exports.GetAutoNumber = (L) => {
    let LeftPad = (number, targetLength) => {
        let output = number + '';
        while (output.length < targetLength) {
            output = '0' + output;
        }
        return output;
    }
    let MaxNumberOfGivenLength = "";
    for (let t = 0;t < L;t++) {
        MaxNumberOfGivenLength = MaxNumberOfGivenLength + "9"
    }
    let StartTime = +new Date();
    let Result = [];
    let ReturnNumber;
    for (let i = 1;i <= MaxNumberOfGivenLength;i++) {
        Result.push(LeftPad(i, L))
    }
    for (let k = 0;k != 26;k++) {
        for (let j = 0;j <= 999;j++) {
            Result.push(String.fromCharCode(k + 65) + LeftPad(j, (L - 1)));
        }
    }
    console.log(Result.length)
    return Result;
}
GetAutoNumber(3)

它将生成结果,例如001-999,A01-A99 ... Z01-Z99

答案 13 :(得分:0)

另一种方法,用于节省内存的学徒:

Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number))

答案 14 :(得分:0)

一个班轮:

new Array(10).fill(1).map( (_, i) => i+1 )

收益:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

答案 15 :(得分:0)

在JavaScript中,绝对应该使生成整数序列更加方便。这是一个递归函数,它返回一个整数数组。

function intSequence(start, end, n = start, arr = []) {
  return n === end ? arr.concat(n)
    : intSequence(start, end, start < end ? n + 1 : n - 1, arr.concat(n));
}

$> intSequence(1, 1)
<- Array [ 1 ]

$> intSequence(1, 3)
<- Array(3) [ 1, 2, 3 ]

$> intSequence(3, -3)
<- Array(7) [ 3, 2, 1, 0, -1, -2, -3 ]

答案 16 :(得分:0)

如果像我一样,您经常使用linspace,则可以像这样轻松地修改linspace版本:

function linSeq(x0, xN) {
    return linspace(x0, xN, Math.abs(xN-x0)+1);
}

function linspace(x0, xN, n){

    dx = (xN - x0)/(n-1);
    var x = [];
    for(var i =0; i < n; ++i){
        x.push(x0 + i*dx);
    }

    return x;
}

然后您可以在任何方向使用linSeq,例如linSeq(2,4)生成2,3,4,而linSeq(4,2)生成4,3,2。

答案 17 :(得分:0)

range(start,end,step):使用ES6迭代器

您可以轻松创建range()生成器函数,该函数可用作迭代器。这意味着您不必预先生成整个数组。

function * range ( start, end, step ) {
  let state = start;
  while ( state < end ) {
    yield state;
    state += step;
  }
  return;
};

现在,您可能要创建一些东西,以从迭代器中预生成数组并返回一个列表。这对于接受数组的函数很有用。为此,我们可以使用Array.from()

const generate_array = (start,end,step) => Array.from( range(start,end,step) );

现在您可以轻松生成静态数组,

const array = generate_array(1,10,2);

但是当某些东西需要迭代器(或为您提供使用迭代器的选项)时,您也可以轻松创建一个迭代器。

for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
  console.log(i)
}

答案 18 :(得分:0)

基于Ariya Hidayat代码的Typescript方法:

/**
 * Generates sequence of numbers from zero.
 * @ param {number} count Count of numbers in result array.
 * @ return {Array<number>} Sequence of numbers from zero to (count - 1).
 */
public static sequence(count: number): Array<number>
{
    return Array.apply(0, Array(count)).map((x, i) =>
    {
        return i;
    });
}

答案 19 :(得分:-1)

为什么不只是简单的连接和拆分?

function seq(len, value)
{
    // create an array
    // join it using the value we want
    // split it
    return (new Array(len + 1)).join(value).split("");
}

seq(10, "a");
["a", "a", "a", "a", "a", "a", "a", "a", "a", "a"]

seq(5, 1);
["1", "1", "1", "1", "1"]