有一种更简单的方法来在没有匿名函数的原型方法上调用过滤器吗?
我想知道是否有相同的myArray.filter(function(it){ it.method() }).
这看起来很接近可能有用的东西(它没有):
function X() {}
X.prototype.method = function() { console.log(this); }
[new X(), new X()].filter(X.prototype.method.call);
Run Code Online (Sandbox Code Playgroud)
相反,我在最新的Firefox和Chrome中都遇到了TypeError,这是因为它不能完全按我的意愿行事:
x = function() { console.log(this) }
x.call(123) //logs 123
y = x.call //reports that y is of type function in console
y(123) //TypeError: Function.prototype.call called on incompatible undefined
y.call(x, 123); //this is what you really need
Run Code Online (Sandbox Code Playgroud)
我尝试使用bind,也许我错过了它,但如果它不是单行,那么它并不比匿名方法形式更好:
function X() {}
X.prototype.method = function() { console.log(this); }
y = X.prototype.method.call
y.bind(X.prototype.method)
[new X(), new X()].filter(y);
Run Code Online (Sandbox Code Playgroud) 使用最新的 Spring Data Mongo(撰写本文时为 2.1.1),如何指定获取“自定义”查询方法的第一条记录?下面是一个例子:
@Query(value="{name: ?0, approval: {'$ne': null}}",
sort="{'approval.approvedDate': -1}",
fields = "{ _id: 1 }")
List<Item> getLatestApprovedIdByName(String name, Pageable pageable);
/**
* Finds the id of the most recently approved document with the given name.
*/
default Item getLatestApprovedIdByName(String name) {
return getLatestApprovedIdByName(name, PageRequest.of(0, 1)).stream().findFirst().orElse(null);
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我可以只使用 String 参数来注释 getLatestApprvedIdByName。org.springframework.data.mongodb.repository.Query注释上似乎没有限制字段。这看起来很奇怪,因为我可以模拟命名方法所做的一切,除了“findFirst”。如果没有 Pageable,我得到IncorrectResultSizeDataAccessException,并且返回 aList是不可接受的,因为我不想浪费时间返回任意大的结果,加上需要处理 0 或 1 个项目的可能性的复杂代码。