为了澄清我的标题,我需要一种方法来确定一个对象不是String,Number,Boolean或任何其他预定义的JavaScript对象.想到的一种方法是:
if(!typeof myCustomObj == "string" && !typeof myCustomObj == "number" && !typeof myCustomObj == "boolean") {
Run Code Online (Sandbox Code Playgroud)
我可以查看是否myCustomObj是一个对象,如下所示:
if(typeof myCustomObj == "object") {
Run Code Online (Sandbox Code Playgroud)
这只适用于原始值,因为这typeof new String("hello world") == "object")是真的.
确定对象是否不是预定义JavaScript对象的可靠方法是什么?
以下是jQuery在jQuery.isPlainObject()中的表现方式
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |