我很難分析其他人的JS代碼的一行Coderbyte挑戰。我們要搜索給定字符串中的所有數字,將它們加在一起,然後返回最終的總和。那麼「88Hello 3World!」應該有91.「55Hello」的輸出應該有55的輸出與「5Hello 5」應該輸出10.我有困難,專門解釋代碼行說:在JavaScript代碼中不理解(variableName!=「」) - Coderbyte挑戰#25:NumberSearch
請幫助我瞭解,這條線特別是在整個功能的上下文中正在做什麼。它完成了什麼?何時會curNum ===「」?你能舉個例子嗎?該生產線是從下面的代碼採取:
function NumberAddition(str) {
var result = 0; //creates var result; sets value to 0
var curNum = ""; //creates var curNum; sets value to ""
for (var i = 0; i < str.length; i++) { //run thru user-inputted string, for each character...
if (str[i] >= "0" && str[i] <= "9") { //if the current element is b/w 0 and 9...
curNum += str[i]; //add the value of that element (as a string) to curNum
else if (curNum != "") *** // ***the 1st part of the if statement is relevant if str[i] is a number. What does this else-if branch do and when does it apply???!
result += parseInt(curNum); // convert curNum to an integer and add it to result variable
curNum = ""; // reset curNum variable to ""/blank
}
}
if (curNum != "") *** // *** again, when does this apply?
result += parseInt(curNum); // take whatever's in curNum and convert to an integer and add to result variable
}
return result; //return result after running thru entire for-loop
}
如果我是採取在它刺傷(讀取黑/白線),代碼的線將當STR [i]是不是數字應用,因此,只要str [i]是數字以外的字符,curNum中的當前值就會轉換爲字符串?不知道這是否合理。但我想我在問什麼,究竟是什麼
curNum != ""
說???並且可以請你展示它是如何工作的例子,當它應用(它的兩個用途)?...
如果它不是空字符串! – adeneo
好吧,那麼這是什麼意思,這行代碼是做什麼的? – Seeeyonnn
它檢查curNum是不是一個空字符串,這就是它所做的,沒有魔法發生。 – adeneo