最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - Create Array with data without looping - Stack Overflow

programmeradmin0浏览0评论

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 weled :)

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

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 weled :)

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

Share Improve this question edited Jul 23, 2011 at 17:32 al7iss asked Jul 23, 2011 at 14:59 al7issal7iss 191 silver badge3 bronze badges 2
  • 1 Your solution has a while loop. – Gaurav 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. – al7iss Commented Jul 24, 2011 at 9:22
Add a ment  | 

9 Answers 9

Reset to default 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.

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

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/ZySst/

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

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(',');

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;
});

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)

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.

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.

发布评论

评论列表(0)

  1. 暂无评论