2017-05-26 110 views
0

如何檢查對象或數組的類型?如何區分對象類型與Typescript中的數組類型

我想添加一個對象(並添加,如果它的對象)某些數組。

//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 is obj parameter OBJECT OR ARRAY*/ 
    var myArray : Array = [1, "a", 3]; 

    function() { 
     myArray.push(obj); 
    } 

    var newMyArray : Array = myArray; 
} 

回答

0

您可以使用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

希望它可以幫助!

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; 
} 
相關問題