问题描述
换句话说,我有什么选择在JavaScript中分配内存?
In other words, what options do I have to allocate memory in JavaScript?
我知道你可以全局或在函数范围内分配内存。我可以动态分配内存吗? new
运算符的真正含义是什么?
I know you can allocate memory either globally, or inside function scope. Can I allocate memory dynamically? What does the new
operator really mean?
编辑:这是一个具体示例。你将如何实现从用户读取整数值 - n
,然后将 n
整数读入数组?
here's a specific example. How would you implement reading an integer value from the user - n
, and then read n
integers into an array?
推荐答案
你无法分配内存。你可以创建对象。这就是 new
的作用。
you can't allocate memory. you can create objects. that's what new
does.
现在,javascript是一个奇怪的生物:函数也是javascript中的对象。所以这意味着你可以使用 new
来实例化所有东西。
now, javascript is a queer creature: functions are also objects in javascript. So this mean that you can instantiate prettymuch everything using new
.
所以, new
运算符表示正在创建新对象。
So, the new
operator means that a new object is being created.
Javascript也可以垃圾收集这些变量,就像在java中一样。因此,如果你了解java,你应该很容易画出相似之处。
Javascript also garbage-collects these variables, just like it happens in java. So if you know java, it should be easy for you to draw parallels.
欢呼,
jrh
PS:当你分配对象时,你真的在分配内存。只是,你没有明确地这样做。您可以分配一个数组,并使其行为类似于内存缓冲区,但这会大大降低javascript的性能:javascript数组不是内存缓冲区,它们也是对象(就像其他所有内容一样)。
PS: when you allocate objects, you really are allocating memory. Only, you are not doing that explicitly. You can allocate an array, and make it behave like a memory buffer, but that will degrade javascript performance drastically: javascript arrays are not in-memory buffers, they are also objects (like everything else).
这篇关于JavaScript有内存堆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!