該程式必須將所有字母放在一起,但它不起作用。我試過除錯器,但沒有顯示任何錯誤。編碼:
var phrase = [ 'h', 'e', 'l', 'l', 'o',' ', 'w', 'o', 'r', 'l', 'd' ];
let sentence: string[] = createSentence(phrase);
sentence.forEach(letter => {
console.log(letter);
});
function createSentence(letters: string[]): string[]
{
var add = "";
var result: string[] = [];
phrase.forEach(unionL => {
if (unionL != ' ') {
add = unionL;
} else {
result.push(add);
add = "";
}
});
return result;
}
uj5u.com熱心網友回復:
由于您在陣列中使用的條件,它不會拉動整個陣列。您需要為要添加到結果陣列的最后一個塊再添加一個條件。這是代碼:
function createSentence(letters: string[]): string[]
{
var add = "";
var result: string[] = [];
phrase.forEach((unionL,index) => {
if (unionL != ' ') {
add = unionL;
} else {
result.push(add);
add = "";
}
//New Code
if(index===phrase.length-1){
result.push(add);
}
});
return result;
}
另一種方法是保留您的代碼,并在字串末尾添加一個與您的邏輯一起使用的空字串。例子:
var phrase = [ 'h', 'e', 'l', 'l', ' ', 'w', 'o', 'r', 'l', 'd', ' ' ];
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/486361.html
標籤:javascript 打字稿
