【发布时间】: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