Set some elements of an array


A

Archos

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
 
Ad

Advertisements

G

Gene Wirchenko

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


Try

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

or

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

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

Sincerely,

Gene Wirchenko
 
M

Michael Haufe (TNO)

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


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))
 
E

Evertjan.

Gene Wirchenko wrote on 26 jan 2012 in comp.lang.javascript:
var b1=[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0];

or

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


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
 
Ad

Advertisements

D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
Try

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

or

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


Try

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

or

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Top