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>
添加回答
舉報