如何在Typescript中区分对象类型和数组类型

时间:2017-05-26 12:18:37

标签: arrays object typescript types

如何检查对象或数组的类型?

我正在尝试添加一个Object(并且只在它的Object中添加它)到某个Array。

=SUMPRODUCT(--(ISNUMBER(FIND(","&5&",",","&A1:A6&","))))

2 个答案:

答案 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
}

请检查https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?v=example

希望它有所帮助!!

答案 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;
}