很難理解陣列中的回圈。嘗試創建感謝卡創建者,這些是我嘗試遵循的步驟:
- 創建一個新的空陣列來保存訊息
- 遍歷輸入陣列并在回圈內使用字串插值為每個名稱構建“謝謝”訊息,然后將該訊息添加到您創建的新陣列中
- 在回圈完成并且所有訊息都已添加到新陣列后,回傳新陣列。
const names = []
function writeCards(names, event) {
for (let i = 0; i < names.length; i ) {
console.log(`Thank you, ${names[i]} for the wonderful ${event} gift!`);
return names;
}
不確定我是否在正確的軌道上。謝謝你的幫助!
uj5u.com熱心網友回復:
我知道您的問題集中在for回圈上,但以防萬一,您可能有興趣使用map更簡潔的方式來實作所需的結果:
const names = ["Joe", "Nina"]
function writeCards(names, event) {
return names.map(name=> `Thank you, ${name} for the wonderful ${event} gift!`)
}
console.log(writeCards(names, "birthday"))
uj5u.com熱心網友回復:
您可以使用 Array.push()
function writeCards(names, event) {
let messages = []
for (let i = 0; i < names.length - 1; i ) {
messages.push("Thank you, " names[i] " for the wonderful " event " gift!")
}
return messages;
}
uj5u.com熱心網友回復:
我寧愿建議使用@DoneDeal0答案。
以防萬一,如果您想使用 for 回圈,還有一種更簡潔的方法可以使用它。您可以使用forEach()javascript給出的函式,因為它有兩個引數,第一個是每個索引的值,第二個是索引號本身。注意:forEach()只是類似于for(i=0; i<n; i ).
names = ["Robert", "King", "Joey"];
function writeCards(names) {
let messages = [];
names.forEach((name, index) => {
messages.push(name);
});
return messages;
}
console.log(writeCards(names));
uj5u.com熱心網友回復:
function writeCards(names, event) {
// 1) Create a new, empty array to hold the messages.
// So, this should be done within the function. We want to be
// able to update this locally-scoped array with the information
// we get from each name in the array, combined with the event
const messages = [];
for (let i = 0; i < names.length; i ) {
// 2) using string interpolation
// What's great is that you've already discovered template strings
// String concatenation has its uses but this far better.
const message = `Thank you, ${names[i]}, for the wonderful ${event} gift!`;
// So, instead of logging the message to the console
// we're going to push it to the messages array
messages.push(message);
}
// 3) After the loop finishes and all of the messages
// have been added to the new array, return the new array.
return messages;
}
console.log(writeCards(['Bob', 'Sue'], 'wedding'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399837.html
標籤:javascript 数组 功能 循环 for循环
下一篇:無字母命令執行
