# 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?

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?

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?

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

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,