我想比較名稱,如果它們匹配,則說我們有相似的名稱,否則我們有不同的名稱。但是這個代碼在比較名字時給出了輸出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