Javascript [object 对象] 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4750225/
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 13:54:05  来源:igfitidea点击:

What does [object Object] mean?

javascriptjquery

提问by Prady

I am trying to alert a returned value from a function and I get this in the alert:

我试图提醒函数的返回值,我在警报中得到了这个:

[object Object]  

Here is the JavaScript code:

这是 JavaScript 代码:

<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
     = $('#1'),
     = $('#2');

.hide(); // hide div#2 when the page is loaded

$main.click(function ()
{
    .toggle();
    .toggle();
});

 $('#senddvd').click(function ()
{
   alert('hello');
   var a=whichIsVisible();
   alert(whichIsVisible());
});

function whichIsVisible()
{
    if (!.is(':hidden')) return ;
    if (!.is(':hidden')) return ;
}

 });

 </script>

whichIsVisibleis the function which I am trying to check on.

whichIsVisible是我要检查的功能。

采纳答案by Felix Kling

The default conversion from an object to string is "[object Object]".

从对象到字符串的默认转换是"[object Object]".

As you are dealing with jQuery objects, you might want to do

当您处理 jQuery 对象时,您可能想要做

alert(whichIsVisible()[0].id);

to print the element's ID.

打印元素的 ID。

As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible())instead of alert.

如评论中所述,您应该使用 Firefox 或 Chrome 等浏览器中包含的工具通过执行console.log(whichIsVisible())而不是alert.

Sidenote: IDs should not start with digits.

旁注:ID 不应以数字开头。

回答by user123444555621

As others have noted, this is the default serialisation of an object. But why is it [object Object]and not just [object]?

正如其他人所指出的,这是对象的默认序列化。但为什么是它[object Object]而不是它[object]

That is because there are different types of objects in Javascript!

那是因为 Javascript 中有不同类型的对象!

  • Function objects:
    stringify(function (){})-> [object Function]
  • Array objects:
    stringify([])-> [object Array]
  • RegExp objects
    stringify(/x/)-> [object RegExp]
  • Date objects
    stringify(new Date)-> [object Date]
  • several more
  • and Object objects!
    stringify({})-> [object Object]
  • 函数对象
    stringify(function (){})->[object Function]
  • 数组对象
    stringify([])->[object Array]
  • 正则表达式对象
    stringify(/x/)->[object RegExp]
  • 日期对象
    stringify(new Date)->[object Date]
  • ……还有几个……
  • Object 对象
    stringify({})->[object Object]

That's because the constructor function is called Object(with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.

那是因为构造函数被调用Object(用大写的“O”),而术语“对象”(用小写的“o”)指的是事物的结构性质。

Usually, when you're talking about "objects" in Javascript, you actually mean"Object objects", and not the other types.

通常,当您在 Javascript 中谈论“对象”时,您实际上指的是对象对象”,而不是其他类型。

where stringifyshould look like this:

哪里stringify应该是这样的:

function stringify (x) {
    console.log(Object.prototype.toString.call(x));
}

回答by alexn

[object Object]is the default toString representation of an object in javascript.

[object Object]是 javascript 中对象的默认 toString 表示。

If you want to know the properties of your object, just foreach over it like this:

如果你想知道你的对象的属性,只需像这样 foreach :

for(var property in obj) {
    alert(property + "=" + obj[property]);
}

In your particular case, you are getting a jQuery object. Try doing this instead:

在您的特定情况下,您将获得一个 jQuery 对象。尝试这样做:

$('#senddvd').click(function ()
{
   alert('hello');
   var a=whichIsVisible();
   alert(whichIsVisible().attr("id"));
});

This should alert the id of the visible element.

这应该提醒可见元素的 id。

回答by Matt Ball

It's the value returned by that object's toString()function.

它是该对象的toString()函数返回的值。



I understand what you're trying to do, because I answered your question yesterdayabout determining which div is visible. :)
The whichIsVisible()function returns an actual jQuery object, because I thought that would be more programmaticallyuseful. If you want to use this function for debugging purposes, you can just do something like this:

我理解你想要做什么,因为我昨天回答了关于确定哪个 div 可见的问题。:)
whichIsVisible()函数返回一个实际的 jQuery 对象,因为我认为这在编程上更有用。如果您想将此函数用于调试目的,您可以执行以下操作:

function whichIsVisible_v2()
{
    if (!.is(':hidden')) return '#1';
    if (!.is(':hidden')) return '#2';
}

That said, you really should be using a proper debuggerrather than alert()if you're trying to debug a problem. If you're using Firefox, Firebugis excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.

也就是说,您确实应该使用合适的调试器,而不是alert()尝试调试问题。如果您使用 Firefox,Firebug非常好。如果您使用的是 IE8、Safari 或 Chrome,则它们具有内置调试器。

回答by Ryosuke Hujisawa

You can see value inside [object Object] like this

您可以像这样在 [object Object] 中看到值

Alert.alert(  JSON.stringify(userDate)  );

Try like this

像这样尝试

    realm.write(() => {
       const userFormData = realm.create('User',{
       user_email: value.username,
       user_password: value.password,
      });
     });

      const userDate = realm.objects('User').filtered('user_email == 
typeof true; //"boolean"
typeof new Boolean(true); //"object"

typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"

typeof 123; //"number"
typeof new Number(123); //"object"
', value.username.toString(), ); Alert.alert( JSON.stringify(userDate) );

reference

参考

https://off.tokyo/blog/react-native-object-object/

https://off.tokyo/blog/react-native-object-object/

回答by Himansh

Basics

基本

You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.

你可能不知道,但在 JavaScript 中,每当我们与字符串、数字或布尔基元交互时,我们就会进入一个隐藏的对象阴影和强制世界。

string, number, boolean, null, undefined, and symbol.

字符串、数字、布尔值、空值、未定义和符号。

In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigintand symbol. Everything else is an object. The primitive types boolean, stringand numbercan be wrapped by their object counterparts. These objects are instances of the Boolean, Stringand Numberconstructors respectively.

在JavaScript中有7种基本类型:undefinednullbooleanstringnumberbigintsymbol。其他一切都是对象。原始类型boolean,stringnumber可以由它们的对象对应物包装。这些对象的实例BooleanStringNumber分别构造。

String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty;            // 5

If primitives have no properties, why does "this is a string".lengthreturn a value?

如果基元没有属性,为什么要"this is a string".length返回值?

Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…

因为 JavaScript 很容易在原语和对象之间进行强制转换。在这种情况下,字符串值被强制转换为字符串对象以访问属性长度。字符串对象只使用了几分之一秒,之后它就会被献给垃圾收集之神——但本着电视发现节目的精神,我们将捕获这个难以捉摸的生物并将其保存起来以供进一步分析……

To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.

为了进一步说明这一点,请考虑以下示例,其中我们向 String 构造函数原型添加了一个新属性。

var myObj    = {lhs: 3, rhs: 2};
var myFunc   = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray  = [2, 3, 5];

myObj.toString();     // "[object Object]"
myFunc.toString();    // "function(){}"
myString.toString();  // "This is a sample String"
myNumber.toString();  // "4"
myArray.toString();   // "2,3,5"

By this means primitives have access to all the properties (including methods) defined by their respective object constructors.

通过这种方式,原语可以访问由它们各自的对象构造函数定义的所有属性(包括方法)。

So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.

所以我们看到原始类型会在需要时适当地强制转换为它们各自的 Object 对应物。

Analysis of toString()method

toString()方法分析

Consider the following code

考虑以下代码

var myObj       = {lhs: 3, rhs: 2};
var myFunc      = function(){}
var myString    = "This is a sample String";
var myNumber    = 4;
var myArray     = [2, 3, 5];
var myUndefined = undefined;
var myNull      = null;

Object.prototype.toString.call(myObj);        // "[object Object]"
Object.prototype.toString.call(myFunc);       // "[object Function]"
Object.prototype.toString.call(myString);     // "[object String]"
Object.prototype.toString.call(myNumber);     // "[object Number]"
Object.prototype.toString.call(myArray);      // "[object Array]"
Object.prototype.toString.call(myUndefined);  // "[object Undefined]"
Object.prototype.toString.call(myNull);       // "[object Null]"

As discussed above, what's really happening is when we call toString()method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString()is equivalent to Number.prototype.toString.call(myNumber)and similarly for other primitive types.

如上所述,真正发生的事情是,当我们toString()在原始类型上调用方法时,必须先将其强制转换为对应的对象,然后才能调用该方法。
ie与其他原始类型myNumber.toString()等效Number.prototype.toString.call(myNumber)并类似。

But what if instead of primitive type being passed into toString()method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString()method of Object function constructor (Object.prototype.toString.call(x))?

但是,如果不是将原始类型传递到toString()其对应的 Object 构造函数对应的方法中,而是强制将原始类型作为参数传递到toString()Object 函数构造函数 ( Object.prototype.toString.call(x)) 的方法中呢?

Closer look at Object.prototype.toString()

仔细看看 Object.prototype.toString()

As per the documentation, When the toString method is called, the following steps are taken:

根据文档,调用 toString 方法时,采取以下步骤:

  1. If the thisvalue is undefined, return "[object Undefined]".
  2. If the thisvalue is null, return "[object Null]".
  3. If this value is none of the above, Let Obe the result of calling toObjectpassing the thisvalue as the argument.
  4. Let class be the value of the [[Class]]internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
  1. 如果this值为undefined,则返回"[object Undefined]"
  2. 如果this值为null,则返回"[object Null]"
  3. 如果此值不是上述任何一个,LetO是调用toObjectthis值作为参数传递的结果。
  4. 让 class 是 的[[Class]]内部属性的值O
  5. 返回字符串值是串联的三根弦的结果"[object "class"]"

Understand this from the following example

从下面的例子中理解这一点

alert({}); // [object Object]

References: https://es5.github.io/x15.2.html#x15.2.4.2https://es5.github.io/x9.html#x9.9https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/

参考资料:https: //es5.github.io/x15.2.html#x15.2.4.2 https://es5.github.io/x9.html#x9.9 https://javascriptweblog.wordpress.com/ 2010/09/27/the-secret-life-of-javascript-primitives/

回答by Brian Donovan

[object Object]is the default string representation of a JavaScript Object. It is what you'll get if you run this code:

[object Object]是 JavaScript 的默认字符串表示形式Object。如果您运行此代码,您将获得以下结果:

var o = {toString: function(){ return "foo" }};
alert(o); // foo

You can change the default representation by overriding the toStringmethod like so:

您可以通过toString像这样覆盖方法来更改默认表示:

##代码##

回答by jondavidjohn

You have a javascript object

你有一个 javascript 对象

$1and $2are jquery objects, maybe use alert($1.text());to get text or alert($1.attr('id');etc...

$1并且$2是 jquery 对象,可能用于alert($1.text());获取文本alert($1.attr('id');等...

you have to treat $1and $2like jQuery objects.

你必须对待$1$2喜欢 jQuery 对象。

回答by Eric Xue

You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString()value is automatically set as "[object Object]".

您正在尝试返回一个对象。由于没有好的方法将对象表示为字符串,因此对象的.toString()值会自动设置为"[object Object]"