2

タイトルを明確にするために、オブジェクトが String、Number、Boolean、またはその他の事前定義された JavaScript オブジェクトではないことを判断する方法が必要です。頭に浮かぶ1つの方法はこれです:

if(!typeof myCustomObj == "string" && !typeof myCustomObj  == "number" && !typeof myCustomObj == "boolean") {

myCustomObj次のように、 がオブジェクトかどうかを確認できます。

if(typeof myCustomObj == "object") {

ただし、これtypeof new String("hello world") == "object")は真であるため、プリミティブ値に対してのみ機能します。

オブジェクトが事前定義された JavaScript オブジェクトではないかどうかを判断する信頼できる方法は何ですか?

4

2 に答える 2

5

jQuery.isPlainObject()で jQuery がそれを行う方法は次のとおりです。

function (obj) {
    // Must be an Object.
    // Because of IE, we also have to check the presence of the constructor property.
    // Make sure that DOM nodes and window objects don't pass through, as well
    if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
        return false;
    }

    try {
        // Not own constructor property must be Object
        if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
            return false;
        }
    } catch(e) {
        // IE8,9 Will throw exceptions on certain host objects #9897
        return false;
    }

    // Own properties are enumerated firstly, so to speed up,
    // if last one is own, then all properties are own.
    var key;
    for (key in obj) {}

    return key === undefined || hasOwn.call(obj, key);
}
于 2012-04-27T20:37:35.117 に答える
4

Object プロトタイプで "toString" 関数を使用できます。

var typ = Object.prototype.toString.call( someTestObject );

これにより、組み込み型の "[object String]" または "[object Date]" などの回答が得られます。残念ながら、単純な Object インスタンスとして作成されたものと、コンストラクターで作成されたものをそのように区別することはできませんが、ある意味では、いずれにせよ、それらのものは実際にはそれほど違いはありません。

于 2012-04-27T20:36:36.317 に答える