我有一个typescript
类,其中有检查变量类型的方法。如何在开始时确定doProcess()
使用哪种方法来处理以下内容?
class MyClass {
public static arr : any[] = [];
// main method
public static doProcess(object : object , justForObjects : boolean = false){
if (justForObjects){
// here should specify which checking method use in *** line
} else {
}
for (let key in object){
if (object.hasOwnProperty(key)){
if (/* *** */){
MyClass.doProcess(object[key] , justObjects)
} else {
MyClass.arr.push(object[key])
}
}
}
return MyClass.arr;
}
// check variables type methods
private static is_object(value : any){
return !!(typeof value === 'object' && !(value instanceof Array) && value);
}
private static is_object_or_array(value : any){
return !!(typeof value === 'object' && value);
}
}
let object = {
'main color' : 'black',
'other colors' : {
'front color' : 'purple',
'back color' : 'yellow',
'inside colors' : {
'top color' : 'red',
'bottom color' : 'green'
}
}
}
MyClass.doProcess(object , true);
我知道它可以在同一个 for 循环中完成(如下所示),但我想先找到一种方法。
for (let key in object){
if(object.hasOwnProperty(key)){
if (justForObjects){
if (MyClass.is_object(object[key])){
// do something
}
} else {
if (MyClass.is_object_or_array(object[key])){
// do something else
}
}
}
}
感谢您的提示