到目前为止,我一直在使用这样的两个函数组合:
// Returns the first element of an array that satisfies given predicate
Array.prototype.findFirst = function (predicateCallback) {
if (typeof predicateCallback !== 'function') {
return undefined;
}
for (var i = 0; i < arr.length; i++) {
if (i in this && predicateCallback(this[i])) return this[i];
}
return undefined;
};
// Check if element is not undefined && not null
isNotNullNorUndefined = function (o) {
return (typeof (o) !== 'undefined' && o !== null);
};
然后我可以使用:
var result = someArray.findFirst(isNotNullNorUndefined);
但是由于ECMAScript中有如此多的函数式数组方法,也许已经有类似的东西存在了?我想很多人都必须一直实现这样的东西...
return (typeof (o) !== 'undefined' && o !== null);
简化为return o != null;
。它们完全等价。 - cliffs of insanity