如何将 JavaScript 对象转换为字符串?
示例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象 { a=1, b=2} // 非常良好易读 :)
条目: [object Object] // 不知道里面是什么 :(
如何将 JavaScript 对象转换为字符串?
示例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象 { a=1, b=2} // 非常良好易读 :)
条目: [object Object] // 不知道里面是什么 :(
我建议使用JSON.stringify
,该函数可以将对象中的变量集合转换为JSON字符串。
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
大多数现代浏览器原生支持该方法,但对于不支持的浏览器,您可以包含一个JS版本。
foo: function () {...}
,则这种方法不起作用。 - Brock AdamsJSON.stringify(obj, null, 2);
以获得更易读的输出结果。 - l.poellabauer"[object Object]"
中恢复对象的真实状态。 - techie_28使用 console
时,只需使用逗号而不是 +
就可以保持简单。 +
会尝试将对象转换为字符串,而逗号会在控制台中分别显示它。
示例:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
输出:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
参考资料: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
console.log(o)
?因为如果您尝试记录添加到字符串中的对象,它实际上会调用该对象的toString()
方法。 - Gocy015console.log
最终调用了名为 Printer
的东西,规范注明:“实现如何打印参数是由实现决定的”,这意味着每个浏览器都可以以不同的方式完成打印(请参见 https://console.spec.whatwg.org/#printer)。Firefox 会将对象显示为漂亮的字符串并带有颜色。Chrome 将对象显示为可展开查看属性的交互式组。试试吧! - Lukeconsole.log('Item:',o);
的输出仍然是Item:[object Object]
。 - Paul Masri-Stoneconsole.dir(o)
代替 console.log
来打印 JavaScript 对象,而不是将其作为字符串打印出来。在开发者工具中,这使得可以打开对象并检查所有属性,甚至包括数组。(参见:https://developer.mozilla.org/de/docs/Web/API/Console/dir) - EagleT当然,要将一个对象转换为字符串,您可以使用自己的方法,例如:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
实际上,以上只是展示了一般的方法;你可能希望使用像http://phpjs.org/functions/var_export:578或http://phpjs.org/functions/var_dump:604这样的东西。
或者,如果你没有使用方法(函数作为对象属性),你可以使用新标准(但不支持旧版本浏览器,尽管你也可以找到一个实用程序来帮助解决这个问题),JSON.stringify()。但是,如果对象使用函数或其他不能序列化为JSON的属性,它将无法工作。
更新:
更现代的解决方案是:
function objToString (obj) {
let str = '';
for (const [p, val] of Object.entries(obj)) {
str += `${p}::${val}\n`;
}
return str;
}
或者:function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
编辑 不要使用此答案,因为它只适用于某些版本的Firefox。其他浏览器不支持它。使用Gary Chambers的解决方案。
toSource()是您要查找的函数,它将以JSON格式写出。
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
toSource()
在IE中不起作用。 - Brett ZamirtoSource()
不是一个被广泛认可的标准,所以无法保证在所有浏览器中都得到支持。 - Gary Chambers一种选项:
console.log('项目: ' + JSON.stringify(o));
另一种选项(正如soktinpk在评论中指出的那样),并且我认为更适合控制台调试:
console.log('项目: ', o);
这里的解决方案都对我没用。很多人说要使用JSON.stringify,但它会忽略函数并且在测试某些对象和数组时似乎存在问题。
我自己想出了一个方案,在Chrome下可以正常工作。在此分享给大家,以便那些在Google上查找的人能够找到。
//Make an object a string that evaluates to an equivalent object
// Note that eval() seems tricky and sometimes you have to do
// something like eval("a = " + yourString), then use the value
// of a.
//
// Also this leaves extra commas after everything, but JavaScript
// ignores them.
function convertToText(obj) {
//create an array that will later be joined into a string.
var string = [];
//is object
// Both arrays and objects seem to return "object"
// when typeof(obj) is applied to them. So instead
// I am checking to see if they have the property
// join, which normal objects don't have but
// arrays do.
if (typeof(obj) == "object" && (obj.join == undefined)) {
string.push("{");
for (prop in obj) {
string.push(prop, ": ", convertToText(obj[prop]), ",");
};
string.push("}");
//is array
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
string.push("[")
for(prop in obj) {
string.push(convertToText(obj[prop]), ",");
}
string.push("]")
//is function
} else if (typeof(obj) == "function") {
string.push(obj.toString())
//all other values can be done with JSON.stringify
} else {
string.push(JSON.stringify(obj))
}
return string.join("")
}
编辑:我知道这段代码可以改进,但一直没有时间去做。用户Andrey提出了一个改进在这里并评论说:
这是有一点改变的代码,它可以处理“null”和“undefined”,并且不会添加过多的逗号。
请自行决定是否使用该代码,因为我没有验证过。欢迎在评论中提出任何其他的改进意见。
console.log('字符串:', obj)
。注意逗号。console.log
的输出通常会在 AJAX 结束并行地提供数组数据之后显示,这会导致误导性的结果。在这种情况下,克隆或序列化对象是可行的方法:因为我们记录了重复的对象,即使 AJAX 完成其工作,它也会填充“旧”的数据。 - rr-$.each(this, function (name, value) {
alert(String(value));
});
更多详情请参见:
(注:此内容为原文,无需翻译)var my_string = ''+value+'';
。 - John Magnolia我正在寻找这个,写了一个带有缩进的深度递归函数:
function objToString(obj, ndeep) {
if(obj == null){ return String(obj); }
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return '{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray];
default: return obj.toString();
}
}
objToString({a: 1, b: {c: "test"}})
if(ndeep > MAX_DEPTH_LEVEL){ return '...'; }
,其中MAX_DEPTH_LEVEL是您选择的最大对象层数。 - SylvainPV
console.log("Item", obj);
。不需要过于复杂的代码。 - soktinpk