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

How can I show any object as string in JavaScript?

本文关键字:对象 显示 字符串 任何 JavaScript      更新时间:2023-09-26

如果我有任何对象,可能是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... }

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

Look JSFiddle

////For NodeJS remove comment below:
//var window = { };
function ToString(obj) {
    clearTimeout(window.ToStringTimeout);
    var result;
    var ident = arguments.length >= 2 ? arguments[1] : undefined;
    if (obj == null) {
        result = String(obj);
    }
    var objString;
    try {
        objString = obj.toString();
    } catch (err1) {
        try {
            objString = String(obj); 
        } catch (err2) {
            try {
                objString = obj + "";
            } catch (err3) {
                objString = "ERROR CONVERT STRING";
            }
        }
    }
    if (!result) {
        window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
        if (window.ToStringRecursive.indexOf(obj) >= 0) {
            result = obj ? (typeof(obj) == "string" ? "'"" + obj + "'"" : objString) : obj;
        } else {
            window.ToStringRecursive.push(obj);
        }
        if (!result) {
            switch (typeof obj) {
                case "string":
                    result = '"' + obj + '"';
                    break;
                case "function":
                    result = obj.name || objString;
                    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 = objString;
                    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"; }
}

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

使用此:

 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] }

像这样:

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

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

效率更高。。。使用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);
}