如何在JavaScript中将任何对象显示为字符串?

时间:2016-08-03 03:33:40

标签: javascript dom

如果我有任何对象,也许new MyObject(),我会显示所有内在属性。我该怎么办?

使用alert(new MyObject())时,结果为[object Object]。但我想要所有的内在属性。例如......

var MyObject = function() {
    this.prop1 = "Hello World";
    this.prop2 = "LOL";
    this.recursive = this;
    this.func = function() { return "func return"; }
}
alert(new MyObject());

在这种情况下,我该如何显示{ prop1 = "Hello World", prop2 = "LOL", etc... }

5 个答案:

答案 0 :(得分:2)

您可以编写此函数并将任何对象转换为string

example

function ToString(obj) {
    clearTimeout(window.ToStringTimeout);

    var result;
    var ident = arguments.length >= 2 ? arguments[1] : undefined;

    if (obj == null) {
        result = String(obj);
    }

    if (!result) {
        window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
        if (ToStringRecursive.indexOf(obj) >= 0) {
            result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : obj.toString()) : obj;
        } else {
            ToStringRecursive.push(obj);
        }
        if (!result) {
            switch (typeof obj) {
                case "string":
                    result = '"' + obj + '"';
                    break;
                case "function":
                    result = obj.name || obj.toString();
                    break;
                case "object":
                    var indent = Array(ident || 1).join('\t'),
                        isArray = Array.isArray(obj);
                    result = '{[' [+isArray] + Object.keys(obj).map(
                        function(key) {
                            return '\n\t' + indent + key + ': ' + ToString(obj[key], (ident || 1) + 1);
                        }).join(',') + '\n' + indent + '}]' [+isArray];
                    break;
                default:
                    result = obj.toString();
                    break;
            }
        }
    }

    window.ToStringTimeout = setTimeout(function() {
        delete window.ToStringTimeout;
        delete window.ToStringRecursive;
    }, 100);

    return result;
}

并使用此:

console.log(ToString(new MyObject()));

显示:

{
    prop1: "Hello World",
    prop2: "LOL",
    recursive: [object Object],
    func: function () { return "func return"; }
}

观察......当任何属性递归时,这不再显示,因为这是无限的。

答案 1 :(得分:2)

使用此:

 var MyObject = function() {
     this.prop1 = "Hello World";
     this.prop2 = "LOL";
     this.recursive = this;
     this.func = function() { return "func return"; } }

 console.log(eval(new MyObject()));

结果是:

{ prop1: 'Hello World',
  prop2: 'LOL',
  recursive: [Circular],
  func: [Function] }

答案 2 :(得分:0)

像这样:

var obj = {type:"Fiat", model:"500", color:"white"};
var str = '';
    
for (var p in obj) {
  str = str + p + " = " + obj[p] + ',';
}
console.log(str);

答案 3 :(得分:0)

%scan()

答案 4 :(得分:0)

效率更高...使用 JSON.stringify 和替换器来驱逐递归属性:

function toString(instance, space = '  ') {
  const objects = [];
  const replacer = (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (objects.findIndex(object => object === value) >= 0) {
        return ({}).toString();
      }
      objects.push(value);
    }
    return value;
  };
  return JSON.stringify(instance, replacer, space);
}