1

I would like to know if it is possible to create an array and initialize it with the same object without having to loop on each element. I don't want to loop because i could have to insert many element . this is what i would like to be able to do:

var array=new Array(10000);

and I would like that each element of the array is the same object (other than undefined :) ) without having to do like this

for(i=0;i<array.length;i++)
    array[i]=object;

I hope that i want to do is clear to you

I came up with a solution but i uses the eval function so I am not sure if it is the best but it much efficient than a loop

Your advises are welcomed :)

here is how

var i="l,",l=new Object(),length=20000;
l.id=1;

while(i.length<length){
      i+=i;
}
i=i.substring(0,length-1);
i="["+i+"]";

var array=eval(i);

console.log(array);

thanks

2
  • 1
    Your solution has a while loop. Commented Jul 23, 2011 at 22:53
  • Yes but I don't loop 10000 times, for 10000 elements I loop only 14 times which is much more efficient. Commented Jul 24, 2011 at 9:22

9 Answers 9

3

There is no requirement for arrays in JS to allocate storage for elements when you do new Array(10000); You are getting undefined elements simply because there are no such elements - even no storage for them allocated. To create elements of the array you have to put them explicitly.

But to be honest I do not understand why do you need that. It is enough to put this:

var v = array[i] || object;

And v will always have either element or the object if element was not defined.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your answer but what I need is that all the elements of the array be the same but not undefined. I need this because I will be modifying the array potion by portion. It does not seem to be doable, I will have to loop over the array witch will decrease performances unfortunately.
Simply add pair of get/set functions to your array like myArr.get = function(i) { return this[i] || object; } and use them instead of [] accessor.
if you really need all elements in an array of fixed length to be a certain Object and not undefined, I don't see how looping would reduce the performance of your program. The javascript environment would have to do it in the background in the same O(N) time that looping provides.
1

No and yes @see array spec.

No, as in JS there is no such constructor like:

var a = new Array(10000, someObject);
// or
var a = Array.fill(0, 10000, someObject);

Yes, as you could do it manually :)

var a = new Array(someObject, someObject, someObject, ..., someObject); // 9996 elements ommited

And in you code it's better to do like this:

for (var i = 0, iMax = array.length; i < iMax; i++) {
    array[i]=object;
}
  1. Add var inside for's counter initialization
  2. Use another local variable instead of array.length, as it a little bit closer in scope

1 Comment

Yes I thought about your solution but the creation of the array is done dynamically and its length is got from a server so it is not always the same.Thanks
1

There is no such in built feature in js but you can create one for you; Yes iam looping inside function myArray.

function myArray(size,defaultObj)
{
    var _array=[];
    for (i=0;i<size;i++)
    {
        _array[i]=defaultObj
    }
    return _array;
}

var myArray= myArray(3,"hello");

alert(myArray[2]);

http://jsfiddle.net/ZySst/

Comments

1

I think this is what you are looking for!

function createMatrix ()
       {
         var matrix = Array.prototype.slice.call(arguments);
         return matrix.length > 0 ? matrix : [0] ;
       }

create matrix of arbitrary dimension createMatrix () --> [0]
createMatrix (1, 2, 3) --> [1,2,3] - vector row

createMatrix ([1], [2], [3]) --> [[1],[2],[3]] - vector column

createMatrix ( [1, 2, 3], [4, 5, 6], [7, 8, 9] )

--> [[1,2,3],[4,5,6],[7,8,9]] - 3 × 3 matrix

Comments

1

I think you can do something like below, I have tried filling 50 1's without using loop, but i think internally split and join both uses loop.

var a = new Array(50).join(1).split('').join(',');

Comments

0

Probably not a practical solution, and won't work in IE < 9, but technically no (explicit) loop:

var a = [];
a.length = 10000;
a.forEach(function(e, i) {
    a[i] = object;
});

2 Comments

Yes but is forEach more efficient than looping ?
Hey, why the downvotes? The question was is it possible. The answer is (technically) yes.
0

No, I don't think that is possible in vanilla JavaScript.

This code will create an Array containing 10 zeros:

var array = [ ] , filler = 1 ;
var i = 0 , length = 10 ;

while(i < length) array.push(filler) , i = i + 1;

alert("(!) array >> " + array) ;

(try it here)

Comments

0

This is the best solution I found, does not use eval and the loop is not too long so the browser does not crash:

var j=0,l=new Object();
l.id=1
var array=[l];

while(array.length<10000){
     array=array.concat(array);
}
array=array.slice(0,10000);
console.log(array.length);

Well of course the bigger the array's length is before the loop, the faster the loop is.

1 Comment

Out of curiosity, have you actually tried some of the simpler patterns using Array#push or the bracket operator in terms of performance. This approach seems a tad bit convoluted tbh. Also, Array#concat creates a new Array with each call (developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…) which seems like a wasteful thing to do.
0

I would say the answer to your question is: it can't be done.

Not in Java, and probably not in any other programming language.

If you think about the underlying machine, what you are asking for is: can a memory area of n values of a specific type be initialized to the same value without looping.

And I guess this is only possible without a loop if there is some special mechanism in the underlying machine, e.g. a way to nullify memory areas. But even then, in most cases the mechanism will in fact loop over all values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.