javascript check if dictionary

后端 未结 7 2384
旧巷少年郎
旧巷少年郎 2021-02-07 11:37

I have a simple program like:

var a = {\'a\': 1, \'b\': 2}
console.log(a)
console.log(a instanceof Array)
console.log(a.constructor instanceof Array)
         


        
7条回答
  •  无人共我
    2021-02-07 11:51

    To be more rigorous you can use JSON. But it's not a performance & memory efficient solution:

    function isJsonable(v) {
        try{
            return JSON.stringify(v) === JSON.stringify(JSON.parse(JSON.stringify(v)));
         } catch(e){
            /*console.error("not a dict",e);*/
            return false;
        }
    }
    

    So the answer can be: (note that it is an inefficient method and is recommended for test purposed only)

    function isDict(v) {
        return !!v && typeof v==='object' && v!==null && !(v instanceof Array) && !(v instanceof Date) && isJsonable(v);
    }
    

提交回复
热议问题