如何使用 TypeScript 查找数组项?(一种现代的,更简单的方法) [英] How do I find an array item with TypeScript? (a modern, easier way)

查看:63
本文介绍了如何使用 TypeScript 查找数组项?(一种现代的,更简单的方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6+ 允许这种简单/干净的方法

ES6+ allows this simple/clean approach

[{"id":1}, {"id":-2}, {"id":3}].find(myObj => myObj.id < 0)  // returns {"id":-2}

TypeScript 实现了许多 ES6+ 特性,并且会继续这样做.看起来它至少有一个同样好的解决方案,所以:

TypeScript implements many ES6+ features and continues to do so. It seems likely it has at least as nice a solution, so:

考虑到易用性、现代最佳实践和简洁优雅,如何使用 TypeScript 在数组中找到项目?
(稍微重申问题以寻求最佳方法)

注意事项

  • "项目"可以是一个 JavaScript 对象,或者几乎任何其他东西.上面的例子恰好是寻找普通的原生JS对象,但是存在很多场景.

  • "item" could be a JavaScript object, or almost anything else. The example above happens to be to find plain ol' native JS objects, but many scenarios exist.

"规范"只是计算机科学(和其他领域)中表达普遍接受的规则或标准公式"的一种奇特方式;(记住这里的每个人在某些时候都不知道)

"canonical" is just a fancy way in Computer Science (and other fields) to say "general accepted rule or standard formula" (remember everyone here didn't know that at some point)

这与新功能无关.任何版本的 JS 都可以做到这一点.然而,随着时间的推移,这种形式的吸引力越来越小.

This is not about new features. Any version of JS could do this. However the form to do so gets less and less appealing the farther you go back in time.

TypeScript 路线图供参考.

推荐答案

第一部分 - Polyfill

Part One - Polyfill

对于尚未实现它的浏览器,array.find 的 polyfill.由 MDN 提供.

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;
  };
}

第二部分 - 界面

您需要扩展开放的 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 查找数组项?(一种现代的,更简单的方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆