Set some elements of an array

Discussion in 'Javascript' started by Archos, Jan 25, 2012.

  1. Archos

    Archos Guest

    I want to initialize an array of 16 elemts to 0

    var b1 = []; for (var i=0; i<16; i++){ b1=0; }

    But, then, I want that the 4 first elements have a value, so I tried
    this one:

    b1 = [1, 2, 3, 4 , b1[4:16]]

    althought it doesn't works. How to get it?
    Thanks in advance
    Archos, Jan 25, 2012
    1. Advertisements

  2. Try

    var b1=[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0];


    var b1=[1,2,3,4];
    for (var i=4; i<16; i++)

    Are you thinking that an array is fixed in size at declaration?
    It is not.


    Gene Wirchenko
    Gene Wirchenko, Jan 25, 2012
    1. Advertisements

  3. JavaScript doesn't use slice syntax. It was proposed at some point,
    but never followed up on AFAIK.

    b1 = [1,2,3,4].concat(b1.slice(4))
    Michael Haufe (TNO), Jan 26, 2012
  4. Archos

    Evertjan. Guest

    Gene Wirchenko wrote on 26 jan 2012 in comp.lang.javascript:

    A variation:

    b = [1,2,3,4].concat([0,0,0,0,0,0,0,0,0,0,0,0]);

    document.write(b.length + ': ' + b);
    // 16: 1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0


    If the added content is not all zero but repeating
    concat() is a good choice:

    var b=[1,2,3,4];
    for (var i=4; i<16; i+=2)
    b = b.concat([9,55]);

    document.write(b.length + ': ' + b);
    // 16: 1,2,3,4,9,55,9,55,9,55,9,55,9,55,9,55
    Evertjan., Jan 27, 2012
  5. In comp.lang.javascript message <[email protected]


    var b1=[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0];


    var b1=[], i=0
    do { b1 = ++i * (i<5) } while (i < 16)

    NOTE - it is well to avoid i & l & o & O for variable identifiers in
    News articles, since you know nothing about the monitors, fonts,
    spelling-checkers, and eyeballs that your avid readers are using.
    Dr J R Stockton, Jan 27, 2012
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.