我正在浏览MDN JavaScript指南,并尝试与the example near the bottom of the page一起使用。
var car = { make: "Ford", model: "Mustang" };
function dump_props(obj, obj_name) {
var result = "";
for (var i in obj) {
console.log(result += obj_name + "." + i + " = " + obj[i] + "<br>");
}
result += "<hr>";
console.log(result);
}
dump_props(car);
我已经修改了原始代码以返回控制台语句但是当我把它放在JSBin.com中时,控制台返回:
"undefined.make = Ford<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br><hr>"
为什么未定义? 感谢
答案 0 :(得分:0)
您的函数dump_props(obj, obj_name)
需要第二个obj_name
参数。但你称它只是传递一个参数:
dump_props(car);
所以,第二个将是undefined
。我想这就是你想要的:
var car = { make: "Ford", model: "Mustang" };
function dump_props(obj, obj_name) {
var result = "";
obj_name = obj_name || obj.constructor.name; // Get the object name
for (var i in obj) {
console.log(result += obj_name + "." + i + " = " + obj[i] + "<br>");
}
result += "<hr>";
console.log(result);
}
dump_props(car);
dump_props(car,"Car"); // Both ways will work
答案 1 :(得分:0)
你没有将参数传递给函数 尝试
dump_props(car,"carclass");
答案 2 :(得分:0)
你的dump_props函数中有一个arguments
太多。
var car = { make: "Ford", model: "Mustang" };
function dump_props(obj) {
var result = "";
for (var key in obj) {
console.log(result += key + " = " + obj[key] + "<br>");
}
result += "<hr>";
console.log(result);
}
dump_props(car);