2017-07-25 102 views
0

作爲練習,我想編寫一個類似於Array.prototype.every()方法的函數all()。只有提供的謂詞對數組中的所有項返回true時,此函數才返回true。如何在Javascript中編寫Array.prototype.every()方法

Array.prototype.all = function (p) { 
    this.forEach(function (elem) { 
    if (!p(elem)) 
     return false; 
    }); 
    return true; 
}; 

function isGreaterThanZero (num) { 
    return num > 0; 
} 

console.log([-1, 0, 2].all(isGreaterThanZero)); // should return false because -1 and 0 are not greater than 0 

不知何故,這不起作用,並返回true。我的代碼有什麼問題?有沒有更好的方法來寫這個?

+0

[什麼是\'返回\'關鍵字的可能的複製\'的forEach \'函數裏面是什麼意思? ](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – juvian

+1

你可能會發現這個鏈接有趣http://reactivex.io/learnrx/並採取看看像lodash這樣的圖書館https://lodash.com/docs/4.17.4 – JGFMK

+0

如果你看看你的控制檯,你會發現你沒有得到-1,0爲真,2爲真。沒有殺死循環時它返回false。你不能用forEach殺死循環,因爲它專門用於運行每個項目。 – Meggg

回答

0

您只能通過拋出異常停止forEach()循環。只需使用正常的for循環即可。

Array.prototype.all = function (p) { 
    for(var i = 0; i < this.length; i++) { 
    if(!p(this[i])) { 
     return false; 
    } 
    } 
    return true; 
}; 

如果不是Array.prototype.every()其他任何方法允許被使用,那麼您可以:

Array.prototype.all = function (p) { 
    return this.filter(p).length == this.length; 
}; 
2

您不能通過返回來跳出Array#forEach循環。改用for循環。

注意:這是部分實施Array#every來演示返回問題。

Array.prototype.all = function (p) { 
 
    for(var i = 0; i < this.length; i++) { 
 
    if(!p(this[i])) { 
 
     return false; 
 
    } 
 
    } 
 
    
 
    return true; 
 
}; 
 

 
function isGreaterThanZero (num) { 
 
    return num > 0; 
 
} 
 

 
console.log([-1, 0, 2].all(isGreaterThanZero));

0

在返回的foreach功能不會從您的函數返回值。你可以這樣編碼。

 Array.prototype.all = function (p) { 
      for(var i = 0; i < this.length; i++){ 
       if (!p(this[i])) 
        return false; 
      }     
      return true; 
     }; 

     function isGreaterThanZero (num) { 
      return num > 0; 
     } 

     var result = [2, 3, 4].all(isGreaterThanZero); 
     console.log("result", result); 
0

其他答案有些不對。您傳遞的回調應該用3個參數調用:當前項目,索引和整個數組。這就是原生Array.every以及大多數本地數組函數的工作原理。你的回調可以選擇使用這些參數,但大部分時間沒有。

Array.prototype.all = function (p) { 
 
    for(var i = 0; i < this.length; i++) { 
 
    if (!p(this[i], i, this)) { 
 
     return false; 
 
    } 
 
    } 
 

 
    return true; 
 
}; 
 

 
function isGreaterThanZero (num) { 
 
    return num > 0; 
 
} 
 

 
console.log([-1, 0, 2].all(isGreaterThanZero)); // should return false because -1 and 0 are not greater than 0

+1

如果你打算使用完整的Array#每個實現,不要忘記添加['thisArg'](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array /每)。 –