2014-09-13 3 views
0
내가 CodeSchool의 운동 중 하나를 수행하고있어

나는 루프 "에 대한"를를 사용하고 싶어하지만 그들은 루프 정상을 사용하고 난 그런 식으로내 생각대로 (내 키 목록)이 작동하지 않는 이유는 무엇입니까?

var canyonCows = [ 
    {name: "Bessie", type: "cow", hadCalf: "Burt"}, 
    {name: "Bertha", type: "cow", hadCalf: null}, 
    {name: "Donald", type: "bull", hadCalf: null}, 
    {name: "Esther", type: "calf", hadCalf: null}, 
    {name: "Burt", type: "calf", hadCalf: null}, 
    {name: "Sarah", type: "cow", hadCalf: "Esther"}, 
    {name: "Samson", type: "bull", hadCalf: null}, 
    {name: "Delilah", type: "cow", hadCalf: null}, 
    {name: "Shanaynay", type: "cow", hadCalf: null} 
]; 

Object.prototype.noCalvesYet = function(){ 
//return true for an object if the object is a cow 
    if(this.hadCalf == null && this.type =='cow') return true; 
    else return false; 
}; 

Array.prototype.countForBreeding = function(){ 
    //this block doesn't work 
    var count = 0; 
    for(c in this) 
    { 
    if(c.noCalvesYet()) ++count; 
    } 
    return count; 

    //this block does work (when i comment out the above block, naturally) 
    // var count = 0; 
    // for(var i = 0; i < this.length;++i) 
    // { 
    // if(this[i].noCalvesYet())count++; 
    // } 
    // return count; 
}; 

//find how many cows haven't had a calf yet and use those for breeding 
alert(canyonCows.countForBreeding()); 
에게
+0

내장 된 프로토 타입 객체에 이러한 함수를 넣는 것은 실제 생산 코드에서 명백하게 의심스러운 디자인 선택 일 것입니다. – Pointy

+0

예. 감사합니다.) 좋은 생각은 아니지만 읽는 방법은 작동 방식의 기본 사항 만 가르치는 것입니다. 머리를 가져 주셔서 고마워. – user3389343

답변

2

자바 스크립트 for ... in 할 필요가 왜 보이지 않아요 루프 이름, 아니 속성 루프.

for (var c = 0; c < this.length; ++c) { 
    var cow = this[c]; 
    if (cow.noCalvesYet()) count++; 
} 

또는를 : 당신이 처음에 for ... in을 사용해서는 안

귀하의 배열은, 어쨌든 실제 숫자 인덱스 배열입니다

this.forEach(function(cow) { 
    if (cow.noCalvesYet()) count++; 
}); 
0

이 허용 대답입니다 :

Object.prototype.noCalvesYet = function() { 
 
    if(this.type == "cow" && this.hadCalf == null){ 
 
    return true; 
 
    } 
 
    return false; 
 
}; 
 
Array.prototype.countForBreeding = function(){ 
 
    var numToBreed = 0; 
 
    for(var i = 0; i<this.length; i++){ 
 
    if(this[i].noCalvesYet()){ 
 
     numToBreed++; 
 
    } 
 
    } 
 
    return numToBreed; 
 
};

관련 문제