Javascript - Initialize an array with zeros

In javascript why

> var myArray = new Array(3);

differs from:

> var otherArray = [*null*, *null*, *null*];

?

Obs: (myArray == otherArray)returns false.

And also, how can I get a type variable otherArray, which is an array full of 'nulls`, but with any size I need?

EDIT

[undefined, undefined, undefined] 

also not equal to myArray.

+4
source share
3 answers

First of all, it should be noted that if you want to compare two arrays or any other object, you will either have to iterate over them or serialize them, since comparing links will always give false


otherArray, , "nulls", , ?

,

function createArray(len, itm) {
    var arr1 = [itm],
        arr2 = [];
    while (len > 0) {
        if (len & 1) arr2 = arr2.concat(arr1);
        arr1 = arr1.concat(arr1);
        len >>>= 1;
    }
    return arr2;
}

,

createArray(9, null);
// [null, null, null, null, null, null, null, null, null]
+3

EcmaScript 6 (ES2105) , , , , :

const arr = new Array(5).fill(null);

MDN

+27

var myArray = new Array(3); . , myArray otherArray . , , undefined, . - , myArray . .

,

var a = new Object();
var b = new Object();
console.log(a===b); // outputs false.

:

var customerA = { name: "firstName" };
var customerB = { name: "firstName" };
console.log(customerA===customerB); // outputs false.

, var myArray = new Array(3) , .

If you try this:

var array = [1,2,3];
console.log(Object.keys(array));

you will get as a result:

["1","2","3"];

If you try this:

var array = new Array(3);
console.log(Object.keys(array));

you will get as a result:

[]
+3
source

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


All Articles