问题描述
有没有规范的方法在TypeScript中查找数组中的对象?
Is there a canonical way to find an object in an array with TypeScript?
我知道TypeScript已经实现了很多ES6功能,ES6可以这样做:
I know TypeScript has implemented a lot of ES6 features, and ES6 can do this:
[{"id":1}, {"id":-2}, {"id":3}].find(myObj => myObj.id < 0)
// returns {"id":-2}
但是我无法在上看到。
However I can't see find on the TS roadmap.
显然,这可以用ES5 Javascript的老式方式完成。关键是TypeScript正在跟踪ES6功能,所以我问是否有更好的方法,最好是上面显示的ES6示例。
Obviously this can be done the old fashioned way with ES5 Javascript. The point is that TypeScript is tracking ES6 features, so I'm asking if a nicer way is possible, preferably something like the ES6 example shown above.
推荐答案
第一部分 - Polyfill
Part One - Polyfill
对于尚未实现它的浏览器, array.find $ c的polyfill $ C>。 。
For browsers that haven't implemented it, a polyfill for array.find
. Courtesy of MDN.
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
第二部分 - 界面
您需要扩展open Array接口以包含 find
方法。
You need to extend the open Array interface to include the find
method.
interface Array<T> {
find(predicate: (search: T) => boolean) : T;
}
当它到达TypeScript时,你会收到编译器的警告会提醒你删除它。
When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.
第三部分 - 使用它
变量 x
将具有预期类型... {id:number}
The variable x
will have the expected type... { id: number }
var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);
这篇关于使用TypeScript在Array中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!