1

I want to declare an array in Jquery to avoid "undefined" I declare like this:

var array = [""];

but It applied for first loop only.

In the second loop array[1], it returns undefined.

How can I declare an array to avoid undefined.

Thank for your help.

5
  • Please add the whole context.. we cannot predict what you are trying to achieve.. Commented Oct 19, 2015 at 7:20
  • Hi. Array is used in for loop. Commented Oct 19, 2015 at 7:24
  • If none of the answers so far have solved the problem, you will need to show more of your code so we can understand the problem better. Commented Oct 19, 2015 at 7:27
  • How do you loop the array? If you do for (var i=0; i<array.length; i++) {} it will not go to position [1]. If you need a fixed length array have a look at stackoverflow.com/questions/4852017/… Commented Oct 19, 2015 at 7:28
  • 1
    Jquery, i do not see any jquery here... Commented Oct 19, 2015 at 7:51

4 Answers 4

2

You may try to create the array before entering the loop by setting its length from the beginning:

var i = 35,
    myArray = new Array(i);

for (i = 0; i < myArray.length; i++) {
    // do something
}

or you can verify if the array contains the element you are trying to use:

var myArray = [""];

for (var i = 0; i < 10; i++) {
    if (myArray[i] === undefined) {
        continue;
    }

    // do something with myArray[i]
}
Sign up to request clarification or add additional context in comments.

Comments

1

Firstly, this is just JavaScript, not jQuery (there's nothing specific to jQuery in that piece of code).

You can only achieve what you are asking if you know the exact number of items in the array. You will need to create a loop to initialise the values of all the items in the array.

Loop to initialise array values

var numberOfItems = 50;
var myArray[];
for (var i=0; i<numberOfItems; i++) {
    myArray.push('');
}

Array of numeric series

Perhaps the range() function in Underscore.js will be useful too if you are wanting a numeric series later: http://underscorejs.org/#range

Comments

1

if you are using this piece of javascript withing a for loop and iterating and you are hitting the "undefined", then the simplest way i can think of is to use the break statement when u hit a "" in the loop and come out of the loop and hence u wont hit "undefined".

Comments

1
var oldVal = ''; 
var array = oldVal.split(',');

after use "array" it's not give "undefined" error.

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.