gpt4 book ai didi

javascript 对象作为参数不返回正确的对象

转载 作者:行者123 更新时间:2023-11-28 19:10:19 26 4
gpt4 key购买 nike

我正在学习 Codecademy 的 JavaScript 类(class),在这门类(class)中我必须返回两个人的较大年龄。由于某种原因,它又回到了年轻的年龄,我一生都无法弄清楚。

// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}
// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2){
return person1.age - person2.age;
}
// Make a new function, olderAge, to return the age of
// the older of two people
function olderAge(){
if(alice > billy){
return alice.age;
}
else{
return billy.age;
}
}


// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

console.log("The older person is " + olderAge(alice, billy));

最佳答案

比较年龄的函数是比较对象而不是对象的 age 参数。所以这个函数:

function olderAge() {
if (alice > billy) {
return alice.age;
} else {
return billy.age;
}
}

应该是:

function olderAge(a, b) {
if (a.age > a.age) {
return a.age;
} else {
return b.age;
}
}

把它们放在一起

我建议将您的代码更改为此 - 我们修复了olderAge:

// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}

// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2){
return person1.age - person2.age;
}

// Make a new function, olderAge, to return the age of
// the older of two people
function olderAge(a, b) {
if (a.age > b.age){
return a.age;
} else {
return b.age;
}
}


// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

console.log("The older person is " + olderAge(alice, billy));

JSFiddle:http://jsfiddle.net/5ae24v92/2/

关于javascript 对象作为参数不返回正确的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com