How to remove all undefined keys from a javascript array (hopefully when creating an array?)

I put my frustrations in jsfiddle to watch here: http://jsfiddle.net/8ShFr/1/

var brand_new_array = new Array();
brand_new_array[10] = "random array value";
alert('why does this array have a length of ' + brand_new_array.length + '???');

I do some client-side calculations that require me to set the keys of the javascript array with the number 1M +.

Not knowing for sure that this number requires me to repeat the first values ​​of 1M + empty arrays before moving on to an array containing data.

I just want to set one big key value for a javascript array without creating empty keys before it?

I use jQuery.each for the array iteration and continue to pass through array[0], array[1], array[2]and so on, when I install only array[123125].

+4
source share
6 answers

Just filteroutside undefineds.

brand_new_array = brand_new_array.filter(function(n){return n !== undefined}); 
+7
source

The reason for the length of 10 is that the length of the array is set to the largest index number in the array. However, this does not mean that there are 9 other values ​​in it, because in javascript the array is at the heart of the object.

Length is just a property of the object. Arrays in javascript are in their main objects (Array Object 1 ). They just act as arrays via api.

" , , , , , , " 1

1. ECMAScript 15.4

+4

, , ( toString() , , ).

var sparse_array_obj = {};
sparse_array_obj[10003210234] = 4; // Fair dice roll
sparse_array_obj[5] = 17; // Truly random number
sparse_array_obj[900] = Math.random(); // Pseudorandom number

for(var i in sparse_array_obj) 
    console.log(sparse_array_obj[i]);

, Javascript ( ). , :

// Sort the keys in numeric order
var sorted_keys = Object.keys(sparse_array_obj).sort(function(a, b){ return a - b; });
for(var i = 0; i < sorted_keys.length; i++)
    console.log(sparse_array_obj[sorted_keys[i]]);

Object.keys shimmed .

+4
var brand_new_array = new Array();
brand_new_array[10] = "random array value";

var result = brand_new_array.filter(function(e) { return e != undefined;})[0];
alert(brand_new_array.indexOf(result));
+1

J . , jQuery.each() , 10 , 0 ( ). API jQuery.each().

, . length (, ) , 0 -1. .

:

var brand_new_array = new Array();
brand_new_array[10] = "random array value";

console.log:

for(var i in brand_new_array) 
  console.log(brand_new_array[i]);

10 console.log:

$(brand_new_array).each( function(i,e) { console.log(e) })

10 console.log:

for (var i=0;i<brand_new_array.length;i++)
  console.log(brand_new_array[i]);

If you really want to use .each(), you can skip undefined indexes as follows:

$(brand_new_array).each( function(i,e) {
    if (this.hasOwnProperty(i)){ console.log(e) } 
})
+1
source

Filter out false elements - including undifined:

var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]
0
source

Source: https://habr.com/ru/post/1524617/


All Articles