为什么这个函数在JS中是returnundefined.property?
Why does this function return undefined.property in JS?
我正在阅读 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);
我已将原始代码更改为 return 控制台语句,但是当我将其放入 JSBin.com 时,控制台 returns:
"undefined.make = Ford<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br><hr>"
为什么未定义?
谢谢
您的函数 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
你没有将参数传递给函数
尝试
dump_props(car,"carclass");
你的 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);
我正在阅读 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);
我已将原始代码更改为 return 控制台语句,但是当我将其放入 JSBin.com 时,控制台 returns:
"undefined.make = Ford<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br>"
"undefined.make = Ford<br>undefined.model = Mustang<br><hr>"
为什么未定义? 谢谢
您的函数 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
你没有将参数传递给函数 尝试
dump_props(car,"carclass");
你的 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);