如何检查对象或数组的类型?
我正在尝试添加一个Object(并且只在它的Object中添加它)到某个Array。
=SUMPRODUCT(--(ISNUMBER(FIND(","&5&",",","&A1:A6&","))))
答案 0 :(得分:1)
您可以使用 Array.isArray()来检查它是否是一个数组,否则添加它
var objToAdd11 : Object = {name: 'Zack', age: 24};
this.addObject(objToAdd11);
//2. should throw errorbecause this is ARRAY, and we need only OBJECTS
var objToAdd22 : Array = [{name: 'Zack', age: 24}];
this.addObject(objToAdd22);
if(!Array.isArray(objToAdd11)){
//add to list
}
希望它有所帮助!!
答案 1 :(得分:0)
您可以Object.keys(obj).length > 0 && obj.constructor === Object
检查对象。希望能帮助到你。
//1. should add this OBJECT to the array
var objToAdd11: Object = {name: 'Zack', age: 24};
this.addObject(objToAdd11);
//2. should throw errorbecause this is ARRAY, and we need only OBJECTS
var objToAdd22: Array = [{name: 'Zack', age: 24}];
this.addObject(objToAdd22);
public addObject(obj: any) : void {
/*I need to check if obj parameter is OBJECT OR ARRAY*/
var myArray: Array = [1, "a", 3];
if(Object.keys(obj).length > 0 && obj.constructor === Object) {
myArray.push(obj);
} else {
console.error("Obj is not an Object");
}
var newMyArray: Array = myArray;
}