【问题标题】:How can I get just cars objects from an array with different types of objects?如何从具有不同类型对象的数组中仅获取汽车对象?
【发布时间】:2016-12-13 03:38:19
【问题描述】:

如何在新数组或循环中仅获取 cars 对象?

type ads = cars | mobiles ;
var add : ads[] = [];
add.push(new cars("Corolla", 800000, 2008));
add.push(new cars ("ferrari", 10000000, 2014));
add.push(new mobiles("nokia", 8000, 3310));
add.push(new cars("mehran", 21, 213));

【问题讨论】:

  • edit你的问题提供一个你想要的结果的例子。此外,包含定义carsmobiles 的代码也会很有帮助。

标签: javascript arrays typescript


【解决方案1】:

您可以将Array.prototype.filter 方法与instanceof operator 一起使用:

let carsArray = add.filter(item => item instanceof cars);

这将创建一个新数组,其中仅包含 add 数组中的汽车实例。

Complete example in playground.

【讨论】:

  • 我只想要新的汽车对象而不是新的手机对象
  • 对,这就是这段代码的作用。 carsArray 将只有 cars 的实例,它们包含在 add 数组中。 mobiles 的实例将不存在。在 Playground 中尝试代码。
猜你喜欢
  • 2023-02-24
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 2021-08-13
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
相关资源
最近更新 更多