简体   繁体   English

Javascript - 用空值初始化数组

[英]Javascript - Initialize array with nulls

In Javascript, why is在 Javascript 中,为什么是

var myArray = new Array(3);

different from:不同于:

var otherArray = [null, null, null];

? ?

Obs: (myArray == otherArray) returns false . Obs: (myArray == otherArray)返回false

And also, how can I get a variable like otherArray , which is an array full of 'nulls`, but with whatever size i'd like?而且,我怎样才能得到一个像otherArray这样的变量,它是一个充满“空值”的数组,但我想要什么大小?

Obs观察者

[undefined, undefined, undefined] 

is also not equal to myArray.也不等于 myArray。

With EcmaScript 6 (ES2105) , creating an array containing five nulls is as easy as this:使用EcmaScript 6 (ES2105) ,创建一个包含five nulls的数组就像这样简单:

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

MDN Reference MDN 参考

This var myArray = new Array(3);这个var myArray = new Array(3); will create an empty array.将创建一个空数组。 Hence, for this reason, myArray and otherArray are different arrays.因此,出于这个原因, myArrayotherArray是不同的数组。 Furthermore, even if they had the same values, three undefined values, the arrays wouldn't be the same.此外,即使它们具有相同的值,三个undefined值,数组也不会相同。 An array is an object and the variable myArray holds a reference to that object.数组是一个对象,变量myArray保存对该对象的引用。 Two objects with the same values aren't the same.具有相同值的两个对象不相同。

For instance,例如,

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

In addition to this:除此之外:

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

Update更新

Furthermore, in the case of var myArray = new Array(3) even the indices aren't initialized, as correctly Paul pointed out in his comment.此外,在var myArray = new Array(3)的情况下,即使索引也没有初始化,正如 Paul 在评论中指出的那样。

If you try this:如果你试试这个:

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

you will get as an output:你会得到一个输出:

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

While if you try this:而如果你试试这个:

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

you will get as output:你会得到作为输出:

[]

The first point to note is that if you want to compare two Arrays or any other Object , you either have to loop over them or serialize them as comparing references will always give false首先要注意的是,如果要比较两个Arrays或任何其他Object ,则必须循环它们或序列化它们,因为比较引用总是会给出false


How can I get a variable like otherArray, which is an array full of 'nulls', but with whatever size I'd like?我怎样才能得到一个像 otherArray 这样的变量,它是一个充满“空值”的数组,但我想要什么大小?

Here is an alternative method for creating Arrays with a default value for its items and all indices initialised:这是创建数组的另一种方法,其项目和所有索引均已初始化:

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;
}

Now,现在,

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

I've did some research and it turned out that the Array(length).fill(null) it not the best solution in terms of performance.我做了一些研究,结果发现Array(length).fill(null)它不是性能方面的最佳解决方案。

The best performance showed:最佳表现显示:

const nullArr = Array(length)
for (let i = 0; i < length; i++) {
  nullArr[i] = null
}

Just look at this:看看这个:

const Benchmark = require('benchmark')
const suite = new Benchmark.Suite

const length = 10000

suite
  .add('Array#fill', function () {
    Array(length).fill(null)
  })
  .add('Array#for', function () {
    const nullArr = Array(length)
    for (let i = 0; i < length; i++) {
      nullArr[i] = null
    }
  })

  .on('cycle', function (event) {
    console.log(String(event.target))
  })
  .on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').map('name'))
  })

  .run({ async: true })

It shows the following results:它显示了以下结果:

Array#fill x 44,545 ops/sec ±0.43% (91 runs sampled)
Array#for x 78,789 ops/sec ±0.35% (94 runs sampled)
Fastest is Array#for

You can also try [...new Array(76)] to generate 76 undefineds.您也可以尝试[...new Array(76)]生成 76 个未定义。

 console.log( [...new Array(76)] )

Or to fill with null .或者用null填充。

 console.log( [...new Array(76).fill(null)] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM