【问题标题】:Object Content returning [object Object]对象内容返回 [object Object]
【发布时间】:2016-08-17 01:17:21
【问题描述】:

试图从我的对象数组中获取文本形式的内容。

var array = [

    first = {
        name: 'first',
        color: 'red',
    },

    second = {
        name: 'second',
        color: 'green',
    },

    third = {
        name: 'third',
        color: 'blue',
    },
];

$('.first').text(first);
$('.second').text(second);
$('.third').text(third);

但是我得到了:

[object Object]

似乎无法在任何地方找到答案,我是否遗漏了一些明显的东西?

codepen demo

【问题讨论】:

  • 什么是[object Object]?
  • 对象转字符串后得到的结果:"" + {}.

标签: javascript jquery json object


【解决方案1】:

您正在调用 JSON 对象。您可以使用点符号获取对象中的内容,例如:

Codepen - dot notation

$('.first').text(first.name + first.color);
$('.second').text(second.name + second.color);
$('.third').text(third.name + third.color);

如果你真的想打印出对象,你可以使用JSON.stringify() like:

Codepen - JSON.Stringify()

$('.first').text(JSON.stringify(first));
$('.second').text(JSON.stringify(second));
$('.third').text(JSON.stringify(third));

【讨论】:

    【解决方案2】:

    首先,如果设置了"use strict" 模式,代码将中断,因为您正在隐式创建全局变量。

    其次,当您调用方法.text() 并设置一个值时,它需要一个stringfunction 值,然后,在这种情况下,方法toString() 被隐式调用对象first, second, third返回"[object Object]",其中Object是对象类型。

    现在,创建数组的正确方法是:

    var list = [
      { name: "first", color: "red" },
      { name: "second", color: "green" }
    ];
    

    或者创建变量:

    var first = { name: "first", color: "red" };
    var second = { name: "second", color: "green" };
    var list = [first, second];
    

    现在我们有了 JavaScript 对象,我们可以创建 JSON 字符串,以便将它们传递给 .text() 方法。

    $(".first").text(JSON.stringify(list[0]));
    // Or...
    $(".first").text(JSON.stringify(first));
    

    PD:您也可以override the methods toString() and valueOf(),但这种方法更加面向对象。

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 2019-03-14
      • 1970-01-01
      • 2017-12-30
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多