我已经简化了我正在处理的功能,但是当运行该功能时,console.log仍然等于0。我做错了什么会导致对象不更新?
var x = { y: 0 };
var z = 5;
function addStrokesToScore(a, b) {
a += b;
}
addStrokesToScore(x.y, z);
console.log(x.y);
答案 0 :(得分:3)
addStrokesToScore(x.y, z)
将x.y
和z
的值传递给函数,它不会传递对属性/变量的引用。您无法更改函数中的属性/变量;没有链接回到它。
这里的正常情况是返回新值:
function addStrokesToScore(a, b) {
return a + b;
}
x.y = addStrokesToScore(x.y, z);
或者,您可以传入对x
对象的引用,并使用该引用更新其y
属性:
function addStrokesToScore(obj, b) {
obj.y += b;
}
addStrokesToScore(x, z);
但总的来说,除非有充分理由,否则您需要使用return
选项。
答案 1 :(得分:1)
问题是你传递的值不是对象引用:
var x = {
y: 0
};
var z = 5;
function addStrokesToScore(o, b) { //note
o.y += b; //note
}
addStrokesToScore(x, z); //note
alert(x.y);

答案 2 :(得分:1)
您正在传递一个不可变的数字。您需要传递对整个对象的引用:
x.y=addStrokesToScore(x.y, z);
答案 3 :(得分:1)
你没有更新x.y的地方,你只是将它传递给fn并更新fn局部变量' a'。
您可以添加public class VirtualFriend {
// variables
private String myName;
private int myAge, myFood;
// other variables
private int a, b;
private VirtualFriend other;
// general constructor
public VirtualFriend() {
myName = "Unknown";
myAge = 5;
myFood = 2;
}
// specific constructor
public VirtualFriend(String myName, int myAge) {
this.myName = myName;
this.myAge = myAge;
myFood = 2;
}
// name methods
public void setName(String myName) {
this.myName = myName;
}
public String getName() {
return myName;
}
// integer method
public int add(int a, int b) {
this.a = a;
this.b = b;
return a + b;
}
// void methods
public void printName() {
System.out.println(myName);
}
public void greet(VirtualFriend other) {
this.other = other;
System.out.println("Hi there " + other + ". It's nice "
+ "to meet you. My name is " + myName + ".");
}
// main method
public static void main(String[] args) {
VirtualFriend Liz = new VirtualFriend("Liz", 16);
VirtualFriend Boo = new VirtualFriend("Boo", 16);
Liz.greet(Boo);
}
}
或将return a添加到函数中,并将调用语句设为z-index
答案 4 :(得分:1)
通过x.y传递值0而不是引用。使用此 -
var x = { y: 0 };
var z = 5;
function addStrokesToScore(a, b) {
a.y += b;
}
addStrokesToScore(x, z);
console.log(x.y);