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函数可以在一次调用时返回一个数字,在另一次调用时可以返回一个字符串。 –
为什么你需要防止这种情况?其他数组方法对此没有任何检查。 – Soviut
@Soviut消息说:'谓词必须是一个函数',而'function(){}'是一个没有任何返回类型的函数。 –