在 Typescript 中,我经常使用这种模式:
class Vegetable {
constructor(public id: number, public name: string) {
}
}
var vegetable_array = new Array<Vegetable>();
vegetable_array.push(new Vegetable(1, "Carrot"));
vegetable_array.push(new Vegetable(2, "Bean"));
vegetable_array.push(new Vegetable(3, "Peas"));
var id = 1;
var collection = vegetable_array.filter( xvegetable => {
return xvegetable.id == id;
});
var item = collection.length < 1 ? null : collection[0];
console.info( item.name );
我正在考虑创建一个类似于 LINQ SingleOrDefault
的 JavaScript 扩展如果它不在数组中,它返回 null
的方法:
var item = vegetable.singleOrDefault( xvegetable => {
return xvegetable.id == id});
我的问题是是否有另一种方法可以在不创建自定义界面的情况下实现这一点?
最佳答案
您可以随时使用 Array.prototype.filter这样:
var arr = [1,2,3];
var notFoundItem = arr.filter(id => id === 4)[0]; // will return undefined
var foundItem = arr.filter(id => id === 3)[0]; // will return 3
编辑
我的回答适用于 FirstOrDefault
而不是 SingleOrDefault
。
SingleOrDefault
检查是否只有一个匹配项,在我的情况下(在您的代码中)您返回第一个匹配项而不检查另一个匹配项。
顺便说一句,如果你想实现 SingleOrDefault
那么你需要改变这个:
var item = collection.length < 1 ? null : collection[0];
进入
if(collection.length > 1)
throw "Not single result....";
return collection.length === 0 ? null : collection[0];
关于javascript - LINQ SingleOrDefault() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065696/