简体   繁体   English

检查数组中是否存在 object 类型

[英]Check if an object type exists in the array

I have an abstract class that call Car.我有一个抽象的 class 调用 Car.

    abstract class Vehicles {
}

I have more 3 classes,which inheritance Car:我还有 3 个班级,其中 inheritance 车:

class Car extends Vehicles {
}

class Motorcycle extends Vehicles {
}

class Truck extends Vehicles {
}

I want to make a random array that his type is Vehicles:我想制作一个他的类型是车辆的随机数组:

let vehicles1: Vehicles [] = new Array(2);

But i don't want repeat the same Vehicles type twice.(There will be no two cars for example) I can check every type the object that was created,but if i have 20 classes that extends Vehicles?但是我不想重复相同的车辆类型两次。(例如,不会有两辆车)我可以检查创建的 object 的每种类型,但是如果我有 20 个扩展车辆的类?

How i can to check if the object, was already created in array or not?我如何检查 object 是否已经在数组中创建? but witout alot of if check?但是没有很多if检查? (typeof) (类型)

thank you.谢谢你。

You can use findIndex to insure there is no other items of the same type, here is an example of the function that adds a new item to the vehicles1 array but before that it tests for any existing items of the same type:您可以使用 findIndex 来确保没有其他相同类型的项目,这里是 function 的示例,它向 Vehicles1 数组添加了一个新项目,但在此之前它会测试任何现有的相同类型的项目:

function addVehicle(vehicle) {
        const thisType = typeof vehicle;

        const index = vehicles1.findIndex(el => typeof el === thisType);
        if(index !== -1) {
            // that means there is no item of the same type, So you can add this one
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM