Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty elements in JS array declaration [duplicate]

it's my first question here, after have been reading for years, so be nice with me please.

I'm having trouble with array management in js/jq.

I have array with several elements, which is processed with $.each function. I want to extract matching elements to another array and return this array. But for some reason (don't know if it's because array declaration, jquery.each function...) I'm having first empty element.

I think I'm making this more difficult to understand than it's, so made jsfiddle.

var arr = new Array();
$.each([1,2,3], function(index,element){
    if (element == 2){
        arr[index] = element;
    }
});

arr must have only 1 element, but arr.length returns 2 because first array slot is empty.

Here is a fiddle http://jsfiddle.net/moay7y95/

I'm so sure that it's a simple and little stupid thing, but I've not been able to find an answer.

Thanks in advance!

like image 694
Guillem Rivas Avatar asked Dec 03 '25 16:12

Guillem Rivas


1 Answers

You are pushing an element in array at 1st index. So, javascript by default put undefined at 0th index.

So, at the end of each your array will be

[undefined, 2];

This is the reason you get the length as 2.

You can use push to add element in array:

$.each([1, 2, 3], function (index, element) {
    if (element == 2) {
        arr.push(element);
        elem++;
    }
});

Demo: https://jsfiddle.net/tusharj/moay7y95/2/

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Docs: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push

like image 123
Tushar Avatar answered Dec 06 '25 08:12

Tushar