gpt4 book ai didi

javascript - javascript中的内存问题

转载 作者:行者123 更新时间:2023-11-30 07:28:26 26 4
gpt4 key购买 nike

每次实例化对象或函数时,它是否存储内存或者只是存储原始值的变量。

例如 - var myArray = new Array();var num = function(){};

最佳答案

当你做的时候

var myArray = new Array();

您在内存中创建一个对象,并在 myArray 变量中存储对该对象的引用。 (引用就像 C/C++ 中的指针。它是一个值,告诉 JavaScript 引擎对象在哪里。)例如:

+−−−−−−−−−+           | myArray |           +−−−−−−−−−+           +−−−−−−−−−−−−−−−−−−−−−−−−−−−−+|   ref   |−−−−−−−−−−>| instance of an array       |+−−−−−−−−−+           +−−−−−−−−−−−−−−−−−−−−−−−−−−−−+                      | length = 0                 |                      +−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

When you do:

var n = 2;

您将实际值 2 存储在 n 中:

+−−−−−−−−−+|    n    |+−−−−−−−−−+|    2    |+−−−−−−−−−+

This is the essential difference between primitive and object types. (It gets a bit blurred with strings, but you can pretend that primitive strings in JavaScript act just like numbers and such, the engine hides some details from you.)

This is an important distinction, because JavaScript is a purely pass by value language, so when you call a function and pass arguments into it, the values, not the variables, are passed. Consider:

function foo(index, a) {
return a[index];
}

foo 函数接受一个索引和一个数组,并返回数组中该索引处元素的值。

x = foo(n, myArray);

调用 foo 函数并传入 n (2) 的 valuevalue myArray(对数组的引用)。因此 index 接收到相同的值 n 具有 (2),并且 a 接收到相同的值 myArray 具有 (对数组的引用)。由于 amyArray 的值是对数组的引用,因此它们都引用同一个数组:

+−−−−−−−−−+| myArray |+−−−−−−−−−+|   ref   |−−−−−−−+    +−−−−−−−−−+       |                      |    +−−−−−−−−−−−−−−−−−−−−−−−−−−−−++−−−−−−−−−+       +−−−>| instance of an array       ||    a    |       |    +−−−−−−−−−−−−−−−−−−−−−−−−−−−−++−−−−−−−−−+       |    | length = 0                 ||   ref   |−−−−−−−+    +−−−−−−−−−−−−−−−−−−−−−−−−−−−−++−−−−−−−−−++−−−−−−−−−+|    n    |+−−−−−−−−−+|    2    |+−−−−−−−−−++−−−−−−−−−+|  index  |+−−−−−−−−−+|    2    |+−−−−−−−−−+

The same is true of assignment statements, and for the same reason: The variable on the left of the = receives the value of the expression on the right of it.

var n2 = n;
var a2 = myArray;

n2接收n的值(2),a2接收myArray的值(a对数组的引用)。如果我们绘制 myArraya2nn2 图表,该图表将与上面的图表相同foo 的参数 indexa

由于myArraya指向同一个数组(引用同一个对象),如果它们对数组执行mutator操作,则通过任一引用都可以看到结果。例如,向数组添加一个新元素是一个增变操作,它改变对象:

alert(myArray.length); // 0
alert(a.length); // 0
a.push("test");
alert(myArray.length); // 1
alert(a.length); // 1

了解那里发生的事情很重要。 变量 myArraya 没有改变,但是它们引用的对象改变了。相反:

a = someOtherArray;

现在 a 完全指向其他地方,它的 value 不再与 myArray 的值相同,因此它不是' 指的是同一个对象。


题外话:更好的写作方式

var myArray = new Array();

var myArray = [];

最终结果是一样的(一个新数组被创建并分配给 myArray),但是第二个更短,效率稍微高一点,并且保证你会得到一个数组(而第一个可能,在不寻常的情况下,不会给你一个数组——如果有人有 shadowed Array 符号)。

同样的,你可以这样写

var obj = new Object();

像这样

var obj = {};

...出于同样的原因,它具有类似的好处。

关于javascript - javascript中的内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com