2015-11-20 120 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傳遞給函數,要麼在函數內部提取該值,以便可以進行正確比較。