2015-11-20 130 views
2

我想比较名称,如果它们匹配,则说我们有相似的名称,否则我们有不同的名称。但是这个代码在比较名字时给出了输出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)); 
+0

当我尝试你的例子时,我得到“我们有不同的名字,鲍勃和我”。这就是你说你想得到的。请修复这个问题来描述真正的问题。 – Barmar

+0

对不起,我的问题不清楚。我想检查名称是否匹配,然后我想打印,我们有相同的名称,我们有不同的名称。 @Barmar – bhordupur

+0

我明白你想要做什么,但是你不能在问题中解释清楚。你能解决它使用一个例子,它给出了错误的结果吗? – Barmar

回答

2

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);

+0

非常感谢Paul Roub :) – bhordupur

2

您比较字符串(this.obj.name)一个对象(othername)。他们不会相同,所以你会一直输出他们有不同的名字。默认情况下,任何函数的返回值都是undefined,除非您另行指定,所以这就是为什么您的输出尾部为undefined

要么将​​eve.obj.name传递给函数,要么在函数内部提取该值,以便可以进行正确比较。