Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push an empty element into javascript array

How can I push empty element to an existing Js array, lets assume :

var arr = [54,77,21];
var target = [54,77,21,,,,36];
arr.push(); //do not append an empty element into the array.
arr.push();

console.log(JSON.stringify(arr)); //output: [54,77,21]

How to append empty elements so "arr" will be equivalent to "target" array?

like image 762
Voice Of The Rain Avatar asked Jul 25 '19 08:07

Voice Of The Rain


2 Answers

You could address the index directly. This builds a sparse array.

var arr = [54,77,21];

arr[6] = 36;
console.log(JSON.stringify(arr));

Or push undefined until you like to push the value. This returns a filled array.

var arr = [54,77,21];

arr.push(undefined);
arr.push(undefined);
arr.push(undefined);
arr.push(36);
console.log(JSON.stringify(arr));

By using JSON.stringify, you get for undefined or sparse items null, because JSON knows only null instead of undefined.

like image 153
Nina Scholz Avatar answered Oct 02 '22 15:10

Nina Scholz


You can use Array#length:

arr.length++;

You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases; for example, if you set length to 3 when it is currently 2, the array now contains 3 elements, which causes the third element to be a non-iterable empty slot.

But note that JSON does not support sparse arrays. I.e. you cannot see empty slots with JSON.stringify.

var arr = [54,77,21];
arr.length++;
arr.length++;
arr.length++;
arr.push(36);
console.log(arr);

(FYI: Stack Snippets do not seem to support sparse arrays correctly. You need to run that code in the browser console instead.)

like image 45
str Avatar answered Oct 02 '22 15:10

str