gpt4 book ai didi

javascript - 需要对象比较帮助

转载 作者:行者123 更新时间:2023-11-29 18:02:36 26 4
gpt4 key购买 nike

我想比较名字,如果匹配,则说我们的名字相似,否则我们的名字不同。但是这段代码在比较名称时给出了输出 undefined

有人可以帮我理解/解决这个问题吗?

我想获得关注,例如:

We have different names, Bob and I.

function addPersonMethods(obj){
this.obj = obj;
}

addPersonMethods.prototype.greet = function(str){
return str + ", my name is "+ this.obj.name;
}

addPersonMethods.prototype.nameshake = function(othername){
this.othername = othername;
if (this.obj.name == this.othername){
console.log("We have the same name ," + this.obj.name + " and I! ");
}
else
console.log("We have different names ," + this.obj.name + " and I.");
}

var bob_def = { name: 'Bob', age: 21 };
var eve_def = { name: 'Eve', age: 21 };

var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({name:'Bob', age: 40});

console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));

console.log(bob.nameshake(eve));

最佳答案

您的 nameshake() 方法需要一个 string(名称),但您传递的是一个对象,因此比较永远不会是 true。您想要与该对象的 .obj.name 进行比较。

其次,您正在记录 bob.nameshake() 的结果,而该函数实际上并未返回任何内容。

当您想打印其他人的名字时,您在“我们有...”语句中打印您的自己的名字。

function addPersonMethods(obj) {
this.obj = obj;
}

addPersonMethods.prototype.greet = function(str) {
return str + ", my name is " + this.obj.name;
}

addPersonMethods.prototype.nameshake = function(otherperson) {
var othername = otherperson.obj.name;

if (this.obj.name == othername) {
console.log("We have the same name, " + othername + " and I! ");
}
else
console.log("We have different names, " + othername + " and I.");
}


var bob_def = {
name: 'Bob',
age: 21
};
var eve_def = {
name: 'Eve',
age: 21
};


var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({
name: 'Bob',
age: 40
});

console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));

bob.nameshake(eve);
bob.nameshake(another_bob);

关于javascript - 需要对象比较帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33817513/

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