【问题标题】:In what instances do we create new memory references in javascript?在什么情况下我们会在 javascript 中创建新的内存引用?
【发布时间】:2021-03-30 04:52:53
【问题描述】:

我在这里遇到了一些关于参考与价值的问题 https://gist.github.com/MeeranB/238e085aac8a9abc53ad8a297b03671c 基本上我已经选择了一个 HTMLCollection,并使用 Array.from 方法将其转换为一个数组,但是我有点困惑,因为使用 Array. from 方法完全创建了一个新数组,因此我假设将这个新数组存储在内存中的不同地址。

我预计只有 divsWithClassArray 对象会在我的 forEach 循环之后发生变化,而不是 divsWithClass HTMLCollection

有没有人解释一下这里的后台发生了什么?

/* Assigns divsWithClass HTMLCollection object value to place 1 in 
memory */

const divsWithClass = document.getElementsByClassName("div-class");

//Assigns Array object to place 2 in memory

const divsWithClassArray = Array.from(divsWithClass);

divsWithClassArray.forEach(div => (div.style.color = "green"));

/* How does divsWithClassArray reference the same memory address as 
divsWithClass
if the array.from method creates a new array and we assign it to a new 
variable? */

【问题讨论】:

  • @EugenSunic 我在问题中添加了一个 github 要点:gist.github.com/MeeranB/238e085aac8a9abc53ad8a297b03671c
  • 抱歉,添加了javascript部分的代码
  • divsWithClass中的对象与divsWithClassArray中的对象相同
  • 数组是新的,数组中每个元素的内容不是...试试这个...const a = [ {x:1}]; const b = a.slice(); b[0].x=2; console.log(a[0].x)(array.slice 也返回一个新数组)——当然如果内容的数组是原语,那么这会有所不同,但你有对象
  • 想想这个...const a = document.getElementById('id'); const b = a; b 和 a 都引用同一个对象...创建数组时您的代码本质上是在循环中执行此操作

标签: javascript reference pass-by-reference


【解决方案1】:

如果你已经知道在这种情况下

const a = {x: 1};
const b = a;

b 和 a 都指向同一个对象 {x:1},因此更改 b.x 更改 a.x - 然后将您的代码视为本质上是这样的

const divsWithClass = document.getElementsByClassName("div-class");
const divsWithClassArray = [];
for (let i = 0; i < divsWithClass.length; i++) {
    divsWithClassArray.push(divsWithClass[i]);
    // or divsWithClassArray[i] = divsWithClass[i]
}

以上是在Array.from 存在于旧时代(2015 年之前?)之前我们必须做的一种方式,并产生与

相同的结果
const divsWithClass = document.getElementsByClassName("div-class");
const divsWithClassArray = Array.from(divsWithClass);

【讨论】:

  • 所以 Array.from 不会创建新的引用,但不会创建新的实例。因此,即使这看起来是一个有趣的答案,也不能完全回答问题
  • @CarmineTambascia - 它确实完全回答了这个问题,但它可能无法完全回答你没有问过的问题,但由于我不知道这个问题,我只能推测是否是这种情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 2023-03-20
  • 2020-10-23
  • 1970-01-01
相关资源
最近更新 更多