为什么我的对象显示为“[object Object]”? [英] Why are my objects showing up as "[object Object]"?
本文介绍了为什么我的对象显示为“[object Object]”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按年龄对一系列记录进行冒泡排序,但我得到的只是:
I'm trying to bubble sort an array of records by age but all I get is:
[object Object],[ object object],[object Object]
[object Object], [object Object], [object Object]
如何让它显示记录的值?
How can I get it to display the values of the record?
students = [
{name: "timothy", age: "9"},
{name: "claire", age: "12"},
{name: "michael", age: "20"}
];
for (var i = 0; i < students.length; i++) {
for (var j = i + 1; j < students.length; j++) {
if (Number(students[i].age) > Number(students[j].age)) {
tempValue = students[j].age;
students[j].age = students[i].age;
students[i].age = tempValue;
}
}
}
alert(students);
推荐答案
默认情况下,JavaScript中的所有对象都转为[object Object]
将它们转换为字符串时(与 alert()
的情况一样)。
By default, all objects in JavaScript turn to "[object Object]"
when they are converted to a string (as is the case with alert()
).
您可以尝试:
-
使用console.log或调试器检查数组(而不是使用alert())
Use console.log or a debugger to inspect the array (instead of using alert())
console.log(students);
//Open your browser's developer tools to see the console.
//Try F12, ctrl+shift+J or ctrl+shift+I as shortcuts
使用 JSON.stringify
函数来序列化对象。
JSON.stringify({a:1});
//yields '{"a":1}'
给你对象自定义toString方法
Give your objects a custom toString method
var x = {
a : 17,
toString: function(){
return 'I have a ' + this.a;
}
};
alert(x); //gives "I have a 17"
这篇关于为什么我的对象显示为“[object Object]”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文