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.

Hai Tien
  • 2,929
  • 7
  • 36
  • 55

4 Answers4

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]
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
1
var oldVal = ''; 
var array = oldVal.split(',');

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

Kushal Vora
  • 342
  • 2
  • 16
Kaushik Maheta
  • 1,741
  • 1
  • 18
  • 27
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

Nerdwood
  • 3,947
  • 1
  • 21
  • 20
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".

flipper
  • 146
  • 3
  • 11