我想知道是否有一种已知的,内置/优雅的方法来查找匹配给定条件的JS数组的第一个元素.AC#等价物将是List.Find.
到目前为止,我一直在使用这样的双功能组合:
// 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);
};
Run Code Online (Sandbox Code Playgroud)
然后我可以使用:
var result …Run Code Online (Sandbox Code Playgroud) 我正在写一个JS webapp客户端.用户可以编辑文本项的列表/树(例如,待办事项列表或备注).我用jQuery操作DOM很多.
用户可以使用键盘上下导航列表(类似于GMail中的J/K键),并执行其他几项操作.这些操作中的许多操作具有镜像"向上"/"向下"功能,例如
$.fn.moveItemUp = function() {
var prev = this.getPreviousItem();
prev && this.insertBefore(prev);
// there's a bit more code in here, but the idea is pretty simple,
// i.e. move the item up if there's a previous item in the list
}
$.fn.moveItemDown = function() {
var next = this.getNextItem();
next && this.insertAfter(next);
// ....
}
Run Code Online (Sandbox Code Playgroud)
现在这个具有两个几乎相同的函数的模式在我的代码中的几个地方重复,因为在列表/树上有许多操作非常对称.
问题:如何优雅地重构这一点以避免代码重复?
到目前为止我提出的琐碎方法是使用.apply()......
$.fn.moveItem = function(direction) {
var up = direction === 'up',
sibling = up ? this.getPreviousItem() : this.getNextItem(),
func = …Run Code Online (Sandbox Code Playgroud)