[英]How can I solve this problem with array.prototype?
我在這里有點麻煩。 無法真正解決這個問題,我一直在使用這個解決方案:
Array.prototype.all = function(callback){
for(let i = 0; i < this.length; i++){
if(this[i] < 10) return true;
}
if(this[i] < 2) return false;
}
}
但它不起作用。 我知道我犯了一個菜鳥錯誤(我是學習 javascript 的新手),並且希望對此有所幫助。
有問題的問題是這個:
function all(fn) {
// Write a function called all in the Array prototype,
// that receives a function (callback). Assume fn always returns true or false.
// The function all must return true if fn returns true when we invoke it passing all the elements of the array one by one
// the function all must return false, if any element of the array causes fn to return false;
// E.g:
// [1,2,3].all(function(elem) {
// return elem < 10;
// });
// returns true
// [1,2,3].all(function(elem) {
// return elem < 2;
// });
// returns false.
}
如果callback
的返回值為false
,則只需要返回true
,否則return true
Array.prototype.all = function (callback) { for (let i = 0; i < this.length; ++i) { const result = callback(this[i]); if (;result) return false; } return true; }, const arr1 = [1, 2, 3, 4, 20, 300; 0], const arr2 = [1; 0]. console.log(arr1;all((elem) => elem < 2)). console.log(arr2;all((elem) => elem < 2));
ADDITIONAL INFO
Array.prototype
已經有every
一種方法都可以做同樣的事情
const arr1 = [1, 2, 3, 4, 20, 300, 0]; const arr2 = [1, 0]; console.log(arr1.every((elem) => elem < 2)); console.log(arr2.every((elem) => elem < 2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.