如何判断一个javascript对象是简单对象还是复杂对象?

发布于 2024-12-05 23:17:44 字数 179 浏览 7 评论 0原文

基本上我需要区分以下两个:

var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}

Basically I need to tell apart the following two:

var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

风柔一江水 2024-12-12 23:17:44

使用 typeof 运算符,您可以确定以下内容:

"number"        Operand is a number
"string"        Operand is a string
"boolean"       Operand is a Boolean
"object"        Operand is an object
"undefined"     Operand is not defined.

已编辑:
正如评论中所建议的,您可能还想检查 value 是否为 null,因为 typeof null 将返回对象。

Using typeof operator you can determine the following:

"number"        Operand is a number
"string"        Operand is a string
"boolean"       Operand is a Boolean
"object"        Operand is an object
"undefined"     Operand is not defined.

Edited:
As it was suggested in a comment you may want to also check if value is null, as typeof null will return object.

清音悠歌 2024-12-12 23:17:44

您可以使用 typeof

typeof 5 == "number";
typeof 1.5 == "number";
typeof true == "boolean";
typeof "word" == "string";
typeof {} == "object";

基本上:

if(obj == null) {
  //null or undefined
}
else if(typeof obj == "object") {
  //It's "complex"
}
else {
  //Primitive or "simple"
}

注意: null 将返回 "object",因此您需要检查它。

You could use typeof:

typeof 5 == "number";
typeof 1.5 == "number";
typeof true == "boolean";
typeof "word" == "string";
typeof {} == "object";

Basically:

if(obj == null) {
  //null or undefined
}
else if(typeof obj == "object") {
  //It's "complex"
}
else {
  //Primitive or "simple"
}

Note: null will return "object", so you need to check for it.

痴骨ら 2024-12-12 23:17:44

问题是不仅仅是 {} 返回“对象”类型

typeof 5 == 'number'
typeof NaN == 'number'
typeof 'test' == 'string'
typeof true == 'boolean'
typeof undefined == 'undefined'    

typeof null == 'object'
typeof /asdf/ == 'object' // this is true in some engines, like Firefox's. Not in V8 (in which it is 'function')
typeof [] == 'object'
typeof {} == 'object'

但是,通过使用 toString 您可以进一步检查:

toString.call(null) == '[object Window]' // or '[object global]' or '[object Null]' - depends on engine
toString.call(/asdf/) == '[object RegExp]'
toString.call([]) == '[object Array]'
toString.call({}) == '[object Object]'

因此,最好的检查方法是:

var test;

test = {};
typeof test == 'object' && toString.call(test) == '[object Object]'; // true

test = [];
typeof test == 'object' && toString.call(test) == '[object Object]'; // false

// et cetera

希望有帮助

The problem is that more than just {} returns a type of 'object'

typeof 5 == 'number'
typeof NaN == 'number'
typeof 'test' == 'string'
typeof true == 'boolean'
typeof undefined == 'undefined'    

typeof null == 'object'
typeof /asdf/ == 'object' // this is true in some engines, like Firefox's. Not in V8 (in which it is 'function')
typeof [] == 'object'
typeof {} == 'object'

But, by using toString you can check further:

toString.call(null) == '[object Window]' // or '[object global]' or '[object Null]' - depends on engine
toString.call(/asdf/) == '[object RegExp]'
toString.call([]) == '[object Array]'
toString.call({}) == '[object Object]'

So, the best way to check is:

var test;

test = {};
typeof test == 'object' && toString.call(test) == '[object Object]'; // true

test = [];
typeof test == 'object' && toString.call(test) == '[object Object]'; // false

// et cetera

Hope that helps

月野兔 2024-12-12 23:17:44

在此注明

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};


var simple  = 5;            // or "word", or 56.78, or any other "simple" object
var complex = { propname    : "propvalue"
              , "otherprop" : "othervalue"
              };

simple.getName();           // returns: "Number"
complex.getName();          // returns: "Object"

Credit here

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};


var simple  = 5;            // or "word", or 56.78, or any other "simple" object
var complex = { propname    : "propvalue"
              , "otherprop" : "othervalue"
              };

simple.getName();           // returns: "Number"
complex.getName();          // returns: "Object"
始终不够爱げ你 2024-12-12 23:17:44

尝试以下操作

if (typeof obj === 'object') {
  // It's complex
} else {
  // It's not
}

Try the following

if (typeof obj === 'object') {
  // It's complex
} else {
  // It's not
}
醉殇 2024-12-12 23:17:44

就您的情况而言:

var simple = 5; // number, not an object
var simple = new Number(5); // now it is an object, but still the value is 5
var complex = {propname: "propvalue", "otherprop": "othervalue"};

for ( property in complex ) {
   if ( complex.hasOwnProperty( property ) )
   {
      alert ( 'composite object' );
      return;
   } else {
      alert ( 'simple object' );
      return;
   }
}

据我从您的问题中了解到的,您需要判断该对象是否具有属性/方法。

In your case:

var simple = 5; // number, not an object
var simple = new Number(5); // now it is an object, but still the value is 5
var complex = {propname: "propvalue", "otherprop": "othervalue"};

for ( property in complex ) {
   if ( complex.hasOwnProperty( property ) )
   {
      alert ( 'composite object' );
      return;
   } else {
      alert ( 'simple object' );
      return;
   }
}

As of what I understand from you question - you need to tell if the object has properties/methods.

任性一次 2024-12-12 23:17:44

您可以创建一个简单的函数,为简单类型返回 true:

function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/)
}

请注意,这将为 NaN 返回 true,因为它被视为数字,而为“未定义”返回 false - 但您可以轻松修改它以适应你的具体情况。

运行下面的代码片段以查看其实际效果

<script>
// return true/false if typeof matches simple regex pattern
function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/);
}

// setup some tests cases
var tests = [
  [1,2,3],
  'hello',
  7,
  { foo: 'bar' },
  NaN
]

// log output of isSimple function against each test case
for( var i in tests ) {
  var value = tests[ i ];
  if( isSimple( value ) ) {
    console.log( 'simple value', value );
  } else {
    console.log( 'not simple', value );
  }
}
  
  
</script>

You could just make a simple function that returns true for simple types:

function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/)
}

Note that this will return true for NaN as it's considered a number, and false for 'undefined' - but you could easily modify this to suit your specific case.

Run the snippet below to see it in action

<script>
// return true/false if typeof matches simple regex pattern
function isSimple( a ) {
    return (typeof a).match(/(number)|(boolean)|(string)/);
}

// setup some tests cases
var tests = [
  [1,2,3],
  'hello',
  7,
  { foo: 'bar' },
  NaN
]

// log output of isSimple function against each test case
for( var i in tests ) {
  var value = tests[ i ];
  if( isSimple( value ) ) {
    console.log( 'simple value', value );
  } else {
    console.log( 'not simple', value );
  }
}
  
  
</script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文