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
 
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
 
D

Dr J R Stockton

In comp.lang.javascript message <1u41i7ttl9evaofuq75ffktd4c9lracvbg@4ax.
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

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top