我想比较名称,如果它们匹配,则说我们有相似的名称,否则我们有不同的名称。但是这个代码在比较名字时给出了输出undefined
。需要对象比较帮助
有人能帮我解决这个问题吗?
我想以下,例如:
我们有不同的名称,鲍勃和我
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));
当我尝试你的例子时,我得到“我们有不同的名字,鲍勃和我”。这就是你说你想得到的。请修复这个问题来描述真正的问题。 – Barmar
对不起,我的问题不清楚。我想检查名称是否匹配,然后我想打印,我们有相同的名称,我们有不同的名称。 @Barmar – bhordupur
我明白你想要做什么,但是你不能在问题中解释清楚。你能解决它使用一个例子,它给出了错误的结果吗? – Barmar