如何使用instanceof确定对象的类型?
How to determine the type of an object using instanceof?
我有一棵对象树,其节点可以是两种类型之一。类型 (类) 具有相同的结构。请告诉我如何检查节点类型?我在这里阅读了很多讨论。如果我理解正确,那么我需要“instanceof”。但是没用。
export class ProductTree {
public value: ProductDirection | ProductBrand | null;
public children: ProductTree[];
}
export class ProductDirection {
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = '';
}
}
export class ProductBrand{
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = "";
}
}
使用“instaceof”的简单示例。第一层的元素仅为 ProductDirection 类型,第二层的元素仅为 ProductBrand
类型
var a = 0;
var b = 0;
for (let val of this.productsTree) {
if (val.value instanceof ProductDirection) {
a++;
}
for (let val1 of val.children) {
if (val1.value instanceof ProductBrand) {
b++;
}
}
}
结果:a = b = 0
问题很可能与您创建 productsTree
的方式有关,而不是与您确定元素类型的方式有关。您的检查器弹出窗口表明您的元素是对象类型,因此您很可能将它们创建为非类型化对象而不是类型化对象 ProductTree/ProductDirection/ProductBrand:
// For that data your instanceof should work
let v: ProductTree[] = [
{ value: new ProductDirection, children: [
{ value: new ProductBrand(), children: null],
{ value: new ProductBrand(), children: null]
]}
]
// For that data your instanceof shouldn't work
let v = [
{ value: {id: 1, name: "direction_1"}, children: [
{ value: {id: 2, name: "brand_1"}, children: null],
{ value: {id: 2, name: "brand_2"}, children: null]
]}
]
我有一棵对象树,其节点可以是两种类型之一。类型 (类) 具有相同的结构。请告诉我如何检查节点类型?我在这里阅读了很多讨论。如果我理解正确,那么我需要“instanceof”。但是没用。
export class ProductTree {
public value: ProductDirection | ProductBrand | null;
public children: ProductTree[];
}
export class ProductDirection {
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = '';
}
}
export class ProductBrand{
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = "";
}
}
使用“instaceof”的简单示例。第一层的元素仅为 ProductDirection 类型,第二层的元素仅为 ProductBrand
类型var a = 0;
var b = 0;
for (let val of this.productsTree) {
if (val.value instanceof ProductDirection) {
a++;
}
for (let val1 of val.children) {
if (val1.value instanceof ProductBrand) {
b++;
}
}
}
结果:a = b = 0
问题很可能与您创建 productsTree
的方式有关,而不是与您确定元素类型的方式有关。您的检查器弹出窗口表明您的元素是对象类型,因此您很可能将它们创建为非类型化对象而不是类型化对象 ProductTree/ProductDirection/ProductBrand:
// For that data your instanceof should work
let v: ProductTree[] = [
{ value: new ProductDirection, children: [
{ value: new ProductBrand(), children: null],
{ value: new ProductBrand(), children: null]
]}
]
// For that data your instanceof shouldn't work
let v = [
{ value: {id: 1, name: "direction_1"}, children: [
{ value: {id: 2, name: "brand_1"}, children: null],
{ value: {id: 2, name: "brand_2"}, children: null]
]}
]