0

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??

Pim Jager
32.2k17 gold badges75 silver badges100 bronze badges
asked Aug 4, 2010 at 6:27
1
  • var a = new Array(); a[1] = 'A'; a[10] = 'B'; console.log(a); [empty, "A", empty × 8, "B"] to be up to date Commented Mar 24, 2018 at 14:02

4 Answers 4

6

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'
};
answered Aug 4, 2010 at 6:33
Sign up to request clarification or add additional context in comments.

1 Comment

but i have need a list of value
1

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);
answered Aug 4, 2010 at 6:34

Comments

1

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';
answered Aug 4, 2010 at 6:35

Comments

1

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);
answered Aug 4, 2010 at 6:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.