[英]Checking for the return type of predicate
Array.prototype.takeWhile = function (predicate) { 'use strict'; var $self = this if (typeof predicate === 'function') { let flagged = false, matching_count = 0, nomatching_count = 0; for (let i = 0; i < $self.length; i++) { let e = $self[i] if (predicate(e)) { if (!nomatching_count) { matching_count++ } else { flagged = true break } } else { nomatching_count++ } } return !flagged ? $self.slice(0, matching_count) : $self } throw new TypeError('predicate must be a function') }; var test = function () { var array = [1, 2, 3, 4, 5]; alert(array.takeWhile(x => x <= 3)) };
<button onclick="test()">Click me</button>
條件后:
if (typeof predicate === 'function') {
}
我想問:如何檢查predicate
的返回類型?
我想防止這種情況:
var array = [1, 2, 3, 4, 5];
alert(array.takeWhile(function () {}));
Javascript函數可以返回任何內容,因此無法預測或推斷其返回類型。 確定返回類型的唯一方法是運行函數並檢查結果的類型。
var result = predicate(e);
if (typeof result === 'undefined') {
throw 'Invalid predicate'
}
請注意,函數的返回類型可以是undefined
,這是空函數將返回的內容。
但是,這似乎是不必要的,因為內置的數組方法無需檢查這種邊緣情況。 例如[1,2,3].filter(function() {});
Array.filter()
方法返回一個空數組,因為提供的函數(謂詞)從不對數組中的任何項目返回true。
console.log( [1,2,3].filter(function() {}) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.