![](/img/trans.png)
[英]How do we create instances of a class in JavaScript using new operator and factory pattern?
[英]In what instances do we create new memory references in javascript?
我在这里遇到了一个参考与价值的问题https://gist.github.com/MeeranB/238e085aac8a9abc53ad8a297b03671c使用 HTMLArray.from 方法将其转换为基本上 I've 数组,但是我对如何在这个新数组 object 上执行 for 循环有点困惑,因为使用 Array.from 方法完全创建了一个新数组,因此我假设将这个新数组存储在不同的地址在 memory 中。
我预计只有 divsWithClassArray Object 在我的 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? */
如果您已经知道在这种情况下
const a = {x: 1};
const b = a;
b 和 a 都指同一个 object {x:1}
所以改变bx
改变ax
- 然后把你的代码想象成这样
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.