2017-03-07 24 views
-1

嘗試搜索失敗。我需要使用while循環來添加「!!!」到字符串數組中每個元素的末尾。我嘗試了幾種不同的方式,其中最近的是:<JS>需要使用while循環添加「!!!」的函數到數組的字符串元素的末尾

var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", 
"He hated the sound of his own voice"]; 

function johnLennonFacts(facts) { 
var newFacts=[]; 
var i = 0; 
while (i < 4) { 

newFacts[i] = facts[i] +="!!!"; 
i++; 
} 
return newFacts; 
} 

必須是所有的JS庫沒有我所知道的。我是新來的代碼(顯然)。我知道可能有更好的方法來做到這一點,但我必須使用while循環。提前致謝。

+2

刪除=從+ =,它會工作 –

+0

你需要更改初始陣列或創建新的? – RomanPerekhrest

+2

'+ ='是一個賦值操作符。如果你只是串聯!!!只需使用'+'。 – scrappedcola

回答

0

如果您所要做的只是追加「!!!」到數組項 - 你可以做到這一點,而無需創建一個新的數組 - 只需改變現有的數組。以下控制檯記錄已更改的陣列。還要記住,它不夠有功能 - 爲了它的工作 - 你也需要調用它。我也改變了它的陣列長度作爲上限 - 而不是硬編碼ti爲4 - 這更好,因爲如果你改變數組的內容 - 你不想擔心改變硬編碼值也是如此。

另外,「+ =」運算符是一種簡短的說法:...
事實[i] = facts [i] +「!!!」 ...;在這種情況下工作,因爲我們正在改變初始數組的值。

//sets the array 
 
var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", 
 
"He hated the sound of his own voice"]; 
 

 
//alters the array when called 
 
function johnLennonFacts(facts) { 
 
    var i = 0; 
 
    while (i < facts.length) { 
 
     facts[i] += "!!!"; 
 
    i++; 
 
    } 
 
    console.log(facts); 
 
    } 
 
    
 
//calls the function to alter the array 
 
johnLennonFacts(facts)

0
var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", 
"He hated the sound of his own voice"]; 

function johnLennonFacts(facts) { 
    var newFacts=[]; 
    var i = 0; 
    while (i < facts.length) { 
     newFacts[i] = facts[i] + "!!!"; 
     i++; 
    } 
    return newFacts; 
} 

console.log(johnLennonFacts(facts)); 
0

試試這個:

var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", 
"He hated the sound of his own voice"]; 

function johnLennonFacts(facts) { 
var newFacts=[]; 
var i = 0; 
while (i < 4) { 

newFacts[i] = facts[i] +"!!!"; 
i++; 
} 
return newFacts; 
} 

你並不需要一個=添加到字符串,因爲你已經設置的字符串。 Btw是+=一個賦值操作符。另外不要忘記在你的代碼中調用你的函數。

-1

這個工作。我沒有必要調用console.log,因爲我運行的JS在IDE中(對於一門課程)關於+ =的說明確實有幫助。感謝所有幫助,真的很感激它。

//sets the array 
 
var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", 
 
"He hated the sound of his own voice"]; 
 

 
//alters the array when called 
 
function johnLennonFacts(facts) { 
 
    var i = 0; 
 
    while (i < facts.length) { 
 
     facts[i] += "!!!"; 
 
    i++; 
 
    } 
 
    console.log(facts); 
 
    } 
 
    
 
//calls the function to alter the array 
 
johnLennonFacts(facts)

相關問題