該函數設計用於計算具有類型的對象:cow和hadCalf:null並將值存儲到numToBreed,我總是在控制檯中獲得零。爲什麼?Javascript布爾和原型
var forestCows = [
{name: "Marcus", type: "calf", hadCalf: null},
{name: "Isaiah", type: "bull", hadCalf: null},
{name: "Lemuel", type: "cow", hadCalf: null},
{name: "Daniel", type: "cow", hadCalf: null},
{name: "Joseph", type: "cow", hadCalf: "Legolas"}
];
Object.prototype.noCalvesYet=function(){
if(this.type=="cow" && this.hadCalf==null){
return true;}
else{return false;}
};
Array.prototype.countForBreeding=function(){
var numToBreed=0;
for(var i=0;i<this.length;i++){
this[i].noCalvesYet();
if(this[i].noCalvesYet===true){
numToBreed++;
}
}
return numToBreed;
};
var store=forestCows.countForBreeding();
console.log(store);
而且我試圖創建一個新的功能,以更好地瞭解內有條件的布爾「如果」
var executeThis=function(){return true;};
executeThis();
if(executeThis===true){console.log(3+5);}
在這種情況下,沒有什麼是控制檯中顯示,爲什麼?
`
`
你能解釋爲什麼它不起作用嗎?我首先調用了這個[i] .noCalvesYet(),並且由於返回了noCalvesYet的值(true或false),那麼它應該可以工作。我需要一個解釋爲什麼它不起作用 –