Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

值和引用 #4

Open
q837477816 opened this issue Apr 5, 2018 · 0 comments
Open

值和引用 #4

q837477816 opened this issue Apr 5, 2018 · 0 comments

Comments

@q837477816
Copy link
Owner

q837477816 commented Apr 5, 2018

最近看到一道题:
function foo(x) {
x.push(4);
x; // [1,2,3,4]
// 然后·
x = [4,5,6];
x.push(7);
x; // [4,5,6,7]
}
var a = [1,2,3];
foo(a);
a; // 是[1,2,3,4],不是[4,5,6,7]

我们都知道js的值类型分两种,简单值和引用值;
简单值总是通过值复制的方式来赋值/传递,包括null、undefined、字符串、数字、布尔值和ES6中的symbol。
引用值则总是通过引用复制的方式来赋值/传递。

但是乍一看这里的函数传参,一下就有点困惑了。仔细思考,我们向函数传递a的时候,实际上是将引用a的一个副本赋值给x,而a仍然指向[1,2,3]。在函数中我们可以通过引用x来更改数组的值(push(4)后变成[1,2,3,4])。但x = [4,5,6]并不影响a的指向,所以a仍然指向[1,2,3,4]。

注意,我们不能通过引用x来更改引用a的指向,只能更改a和x共同指向的值。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant