我正在阅读 MDN 文档,但我无法理解下面关于数组文字的陈述。
MDN Array literals
If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.
最佳答案
这意味着:
const arr = [1, 2, 3];
每次执行语句时都会创建一个新数组,而不是一遍又一遍地重复使用同一数组。
这很重要,因为数组在 JS 中是可变的。请参阅下面的代码:
function list() {
return [1, 2, 3];
}
const arr = list();
arr[0] = 42;
console.log(list());
如果没有您引用的规范,第二行可能会输出 [42, 2, 3]。
说到这个话题,我想到了caml。在这种语言中,字符串文字仅分配一次。这可以节省内存,但由于字符串是可变的(在 caml 中),您可以观察到上述行为。
关于javascript - 数组文字何时创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74887234/