如何将引用变量设置为null?

时间:2016-09-19 19:52:34

标签: javascript arrays reference

这是我的用例:

在Phaser.io上,当用户点击按钮时,我将Phaser.sprite设置为本地let newSquare变量,并将.push()设置为Phaser的Squares数组。子画面。

稍后,我在destroy变量上调用了一些newSquare函数,然后将其设置为null。虽然精灵在.destroy()之后很好地从屏幕移除,但我仍然可以从我的Squares数组中访问它...

我认为,作为一个对象,如果我将newSquare变量设置为null,它也会被设置为null以用于所有其他引用,不应该吗?

那么为什么Squares数组中的引用不能设置为null?

摘录:

eventFunction ( e, i ) {
      let newSquare = Game.add.sprite( Lines.attack.a, 0, 'square');

      // Some other methods call here
      Squares[ e.target.dataset.line ].push( newSquare );

      setTimeout( () => {
        if ( newSquare ) {
          newSquare.destroy();
          newSquare = null;
          console.log(Squares); // will print an array with an iteration corresponding to newSquare object, when I want it to be set to null, in order to clean the array with a _.pull()
        }
      }, ( 2 * 1000 ) );

}

我在这里缺少什么?谢谢你。

1 个答案:

答案 0 :(得分:2)

您只是取消对最初创建的对象的引用。该对象仍然存在于内存中,并通过数组访问引用它。这意味着它不会收集垃圾。您需要在数组中使其无效...

以下是您问题的简化版本。

let x = {a: 1, b: 2, c: 3};
let y = x;

x = null;
console.log(y);
// => {a: 1, b: 2, c: 3}

我要说保留对内存中项目的引用,并使用该引用来查找push编辑到的数组中对象的索引。如,

array.find(el => el === reference)

...其中reference是您之前分配给null的标识符。

使元素无效并在阵列中保持其当前位置的方法是使用reference在您的集合上进行映射以找到您的项目。如,

array = array.map(el => el === reference ? null : el)

如果您正在寻找一种可以在原地修改元素的改变方法,请使用forEach(..)。如,

array.forEach((x, i, arr) => {
  if (x === reference) {
    arr[i] = null;
  }
  return;
});

forEach调用将访问数组中的每个元素,因此如果您想要使迭代短路,请尝试使用indexOf循环。

const i = array.indexOf(reference);
array[i] = null;
相关问题