We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
最近看到一道题: 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]
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共同指向的值。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
最近看到一道题:
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共同指向的值。
The text was updated successfully, but these errors were encountered: