3 回答

TA贡献1860条经验 获得超8个赞
您可以return像这样使用您的功能。
因为您没有返回任何值。那西undefined
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
return "<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price;
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
document.write(describe(instantRamen.name, instantRamen.ingredients, instantRamen.price));
document.write(describe(Bagel.name, Bagel.ingredients, Bagel.price));
<html>
<body>
<p id = "p"></p>
</body>
</html>
我已经删除document.write
了return
字符串。

TA贡献1831条经验 获得超9个赞
问题是你在函数describe
内部调用document.write
函数。它写undefined因为 describe 什么都不返回。
发生的事情是:首先,describe
函数在文档中写入 html 文本。然后,您尝试describe
在文档中编写函数的返回。
您不需要将describe
函数放在里面,document.write.
只需使用您想要的参数调用它即可。

TA贡献1848条经验 获得超2个赞
现在它的工作
<html>
<body>
<p id = "p"></p>
<script>
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
document.write("<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price );
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
//edited
describe(instantRamen.name, instantRamen.ingredients, instantRamen.price);
describe(Bagel.name, Bagel.ingredients, Bagel.price);
document.getElementById("p").innerHTML = "Your browser version is " + navigator.appVersion;
</script>
</body>
</html>
添加回答
举报