javascript 检查字典是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38304401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:18:10  来源:igfitidea点击:

javascript check if dictionary

javascript

提问by aryan

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)

Here value of ais dictionary. I want to check for it.

这里的值a是字典。我想检查一下。

How can I check in javascript. My both test above gives me false value

我如何检查javascript。我上面的两个测试都给了我错误的值

I am new to javascript

我是 javascript 新手

回答by Floyd

The simplest approach to check if something is a dictionary in Javascript in a way that will notalso return truewhen given an array is:

以在给定数组时也不会返回的方式检查某事物是否是 Javascript 中的字典的最简单方法true是:

if (a.constructor == Object) {
    // code here...
}

This was inspired by the answer here.

这是受到这里答案的启发。

回答by kofifus

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

回答by jfriend00

The structure {'a': 1, 'b': 2}is a Javascript object. It can be used sort of like a dictionary, but Javascript does not have an actual dictionary type.

该结构{'a': 1, 'b': 2}是一个 Javascript 对象。它可以像字典一样使用,但 Javascript 没有实际的字典类型。

console.log(typeof a);            // "object"
console.log(Array.isArray(a));    // false, because it's not an array

If you want to know if something is an array, then use:

如果你想知道某个东西是否是一个数组,那么使用:

Array.isArray(a)

If you want to know if something is an object, then use:

如果您想知道某物是否是对象,请使用:

typeof a === "object"

But, you will have to be careful because an Array is an object too.

但是,您必须小心,因为 Array 也是一个对象。



If you want to know if something is a plain object, you can look at what jQuery does to detect a plain object:

如果你想知道某个东西是否是一个普通对象,你可以看看 jQuery 是如何检测一个普通对象的:

isPlainObject: function( obj ) {
    // Not plain objects:
    // - Any object or value whose internal [[Class]] property is not "[object Object]"
    // - DOM nodes
    // - window
    if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
        return false;
    }

    // Support: Firefox <20
    // The try/catch suppresses exceptions thrown when attempting to access
    // the "constructor" property of certain host objects, ie. |window.location|
    // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
    try {
        if ( obj.constructor &&
                !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
            return false;
        }
    } catch ( e ) {
        return false;
    }

    // If the function hasn't returned already, we're confident that
    // |obj| is a plain object, created by {} or constructed with new Object
    return true;
},

回答by Sohail Si

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

为了更严格,您可以使用 JSON。但这不是性能和内存高效的解决方案:

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);
}

回答by Jagannath Swarnkar

You can use this to check either your dict(data) is a dictionary or not !

您可以使用它来检查您的 dict(data) 是否是字典!

var dict = { a: 1, b: { c: 3, d: 4 }, e: 9 };

// this function will true / false

const isDict = dict => {
  return typeof dict === "object" && !Array.isArray(dict);
};

console.log(isDict(dict));  // true

this will return you true if it is a dictionary otherwise return false

如果它是字典,这将返回 true 否则返回 false

回答by Pavan Varyani

I use the toStringmethod in Object.prototype, works like a charm in all the cases(Array,null,undefined etc).

我在 Object.prototype 中使用toString方法,在所有情况下(数组、空值、未定义等)都像一个魅力。

var array_var=[1,2];
var dict_var={
'a':'hey',
'b':'hello'
};
console.log(Object.prototype.toString.call(dict_var) === '[object Object]');//returns true
console.log(Object.prototype.toString.call(array_var) === '[object Object]');//returns false  

In short the toString method is used to represent the object, for example the toString method for an array returns '[object Array]'

总之toString方法是用来表示对象的,比如数组的toString方法返回'[object Array]'

回答by David Alvarez

Would that work ?

那行得通吗?

function isDictObj(obj: any) {
  try {
    const test = {...obj}
  } catch(err) {
    return false
  }
  return true
}

My logic is that if it is a dictionnary object (key:values), then using spread operator with {} should work, otherwise throw an exception

我的逻辑是,如果它是一个字典对象 (key:values),那么使用带有 {} 的扩展运算符应该可以工作,否则抛出异常