[英]Check if an object type exists in the array
我有一個抽象的 class 調用 Car.
abstract class Vehicles {
}
我還有 3 個班級,其中 inheritance 車:
class Car extends Vehicles {
}
class Motorcycle extends Vehicles {
}
class Truck extends Vehicles {
}
我想制作一個他的類型是車輛的隨機數組:
let vehicles1: Vehicles [] = new Array(2);
但是我不想重復相同的車輛類型兩次。(例如,不會有兩輛車)我可以檢查創建的 object 的每種類型,但是如果我有 20 個擴展車輛的類?
我如何檢查 object 是否已經在數組中創建? 但是沒有很多if檢查? (類型)
謝謝你。
您可以使用 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.