3

I have created the following array indexes dynamically

var array=[];
array[4]=[];
array[6]=[];
array[100]=[];

then i have tried to add some data on that indexes

array[4].push({"id":3,"name":"dhaval"});
array[6].push({"id":6,"name":"harsh"});
array[100].push({"id":9,"name":"kevin"});

then when i am using the $.each for retrieving the data the $.each loop throught 0 to 100 .

$.each(array,function(key,item){
    console.log(item);
});

the problem is i have to check every time that is item is not undefined then and then the data might exists. so what is the possible solutions for loop only three times not the 100 times.

output :

4 undefined javascript_Each.html:23

[Object] javascript_Each.html:23

undefined javascript_Each.html:23

[Object] javascript_Each.html:23

93 undefined javascript_Each.html:23

[Object]

2
  • 1
    loop will execute 100 time, However you can check item is defined or not Commented Dec 19, 2016 at 12:20
  • Add: if(item!==undefined) to your loop... Commented Dec 19, 2016 at 12:24

3 Answers 3

7

You can use the native forEach function instead of the jQuery each function. The forEach callback is not invoked for uninitialized values. That looks like this:

var array = [];
array[4] = [];
array[6] = [];
array[100] = [];
array.forEach(function(item, key) {
  console.log(item);
});

In this case, the callback is invoked only three times.

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

1 Comment

thanx for this one bro @jobB
1

It's happen because the $.each execute just the function if the value (item) be different of undefined.

If you run this code will show all positions:

for (var i = 0; i < array.length; i++) {
  console.log(i, array[i]);
}

Comments

0

You can use forEach

var a = ["a", "b", "c"];

a.forEach(function(element) {
    console.log(element);
});

// a
// b
// c

And eval() to define dynamically variables

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.