views:

54

answers:

4

hi all ,

var a = new array();
a[1] = 'A';
b[10] = 'B';
console.log(a);
/*[undefined, "A", undefined, undefined, undefined, undefined, undefined, undefined,
  undefined, undefined, "B"]*/

I want to remove undefined element but what is the process??

+1  A: 

well, to remove those undefined parts do

a[0] = 'A';
a[1] = 'B';

In your snippet, you fill the element with index 10 which forces the ECMAscript to create an array with 10 fields. There are no definitions for all that fields between 1 and 10, which means those are correctly undefined.

To remove that fields you either have to set a proper value or map the non-undefined values into a new array which would just be unnecesarry if you create a correct array in the first place.

Create an true object instead of an array (which actually also is an object) to have your desired behavior.

var a = {};

a[1] = 'A';
a[2] = 'B';

console.log(a);
jAndy
but i need index number as so i have done :(
Hasan
+5  A: 

First of all, jQuery has nothing to do with this.

Second, arrays are "autofilled". If you define index 10, all indexes 0 - 9 will be occupied automatically, that's just the way Javascript arrays work.

What you're looking for is probably an object:

var a = {};
a[1] = 'A';
a[10] = 'B';

or

var a = {
    1 : 'A',
    10 : 'B'
};
deceze
but i have need a list of value
Hasan
+1  A: 

In this case you can use an Object instead of an Array like so:

var a = {}; // or var a = new Object();
a[1] = 'A';
a[10] = 'B';
a['foo'] = 'bar';
a.bar = 'foo'; // same as a['bar'] = 'foo';
console.log(a);
Igor Zinov'yev
+1  A: 

Arrays always start at 0 and then go up to the last filled index. You could use an object to solve your problem:

var a = {};
a[1] = 'A';
a[10] = 'B';
alopix