简体   繁体   English

检查谓词的返回类型

[英]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> 

After the condition: 条件后:

if (typeof predicate === 'function') {

}

I want to ask: how to check the return type of predicate ? 我想问:如何检查predicate的返回类型?

I want to prevent this case: 我想防止这种情况:

var array = [1, 2, 3, 4, 5];
alert(array.takeWhile(function () {}));

Javascript functions can return anything so there's no way of predicting or inferring their return type. Javascript函数可以返回任何内容,因此无法预测或推断其返回类型。 The only way to determine the type of what's been returned is to run the function and check the type of the result. 确定返回类型的唯一方法是运行函数并检查结果的类型。

var result = predicate(e);
if (typeof result === 'undefined') {
    throw 'Invalid predicate'
}

Notice that the return type of a function can be undefined , which is what an empty function will return. 请注意,函数的返回类型可以是undefined ,这是空函数将返回的内容。

However, this seems unnecessary since built in array methods don't have any check for this sort of edge case. 但是,这似乎是不必要的,因为内置的数组方法无需检查这种边缘情况。 For example [1,2,3].filter(function() {}); 例如[1,2,3].filter(function() {}); the Array.filter() method returns an empty array because the supplied function (predicate) never returns true against any items in the array. Array.filter()方法返回一个空数组,因为提供的函数(谓词)从不对数组中的任何项目返回true。

 console.log( [1,2,3].filter(function() {}) ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM