我正在尝试按年龄对一组记录进行冒泡排序,但我得到的只是:
[object Object], [object Object], [object Object]
如何让它显示记录的值?
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()
的情况)。
你可以尝试:
使用 console.log 或调试器检查数组(而不是使用 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 方法
var x = { a : 17, toString: function(){ return 'I have a ' + this.a; } }; alert(x); //gives "I have a 17"
关于javascript - 为什么我的对象显示为 "[object Object]"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8022288/