在JavaScript中,实际上是否可以通过数组作为参考?

发布于 2025-01-27 15:49:17 字数 805 浏览 3 评论 0原文

在JavaScript中,是否有可能将数组(从外部范围)传递到函数并突变原始数组?

我已经阅读了一些答案,提到f()'s arr参数实际上是一个副本,它的名称只是阴影外部范围变量。其他提到的数组是始终通过引用传递的,但被“复制”(这是一个令人困惑的解释)。

但是,如果是这样,为什么arr [0] ='a';在外部范围中找到arr参考?但是arr = ['a','b']没有?

如果arr = ['a','b']在功能中使用blockscoped var type(let, const )声明 in

let a = [0,0,1,1,1,2,2,3,3,4];

function f(arr, z) {
  arr[0] = 'a';
  arr = ['a', 'b']
}
f(a);
console.log(a);
[ 'a', 0, 1, 1, 1, 2, 2, 3, 3, 4 ]
  1. f()函数中,

    arr [0] ='a'a'修改arr 外部范围

  2. 中修改arr,但参考arr = (没有让或 const`)也应参考外部范围?

Is it possible in Javascript to pass an array (from outer scope) to a function, and mutate the original array?

I've read several answers mentioning that f()'s arr argument is actually a copy, it's name just shadows the outer scope variable. Other mention arrays are always passed by reference, but are 'copied' (that is a confusing explanation).

But if that is the case, why does arr[0] = 'a'; find the arr reference in outer scope? But arr = ['a', 'b'] does not?

If arr = ['a', 'b'] was declared in the function with a blockscoped var type (let, const), that would make more sense..

let a = [0,0,1,1,1,2,2,3,3,4];

function f(arr, z) {
  arr[0] = 'a';
  arr = ['a', 'b']
}
f(a);
console.log(a);
[ 'a', 0, 1, 1, 1, 2, 2, 3, 3, 4 ]
  1. From within f() function, the line arr[0] = 'a' modifies arr in the outer scope

  2. But the reference arr =(without aletorconst`) should also refer to outer scope?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余生一个溪 2025-02-03 15:49:17

第一件事是数组在JavaScript中始终作为参考传递。

现在来到您的问题时,当数组传递给函数时,该函数的参数变量将保持该引用,在您的情况下,它是ARR参数。如果您突变ARR,它将突变原始数组,因为它是指原始数组在那个数组上。

First thing is arrays are always passed as reference in javascript.

Now coming to your question, when an array is passed to a function the argument variable of that function will hold that reference, in your case it's arr argument. If you mutate arr it will mutate original array as it is referring to original array but if you just assign some other value or reference to arr it will no longer hold reference to that original array and any changes to new reference won't have any effect on that array.

虫児飞 2025-02-03 15:49:17

JavaScript按价值传递。但是,当将对象作为参数传递时,值是参考。

数组是一个对象。修改对象的属性时,更改即使在函数范围之外也会反映。因此,修改一个项目(例如,数组的属性)会产生上述效果。但是,替换对象只能替换所述参考点朝向的值,因此更改仅在函数范围内反映。

JavaScript is pass by value. However, when passing an object as a parameter, the value is the reference.

An array is an object. When modifying the property of an object, the change will be reflected even outside of the function scope. Thus, modifying one item (e.g, a property of the array) produces said effect. However, replacing the object will only replace the value to which said reference points toward, thus the change will only be reflected within the scope of the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文