[英]How to get value from the inside of for loop in javascript?
我需要Typescript(javascript)幫助,等待for循環中的代碼先完成
我有輸入(文本框)從用戶那里獲取字符串並在其中搜索#Number(#50),我已經完成了一個讀取'#'起始索引的功能,我只需要在#之后獲取數字,使用for循環將每個字符與SPACE進行比較以讀取數字值,但我相信它在for循環完成之前返回的返回值如何使返回等待FOR循環完成並在返回之前更新內部變量值回...
readNumber(text: string): number {
const start = text.indexOf('#') + 1;
let newText = '';
for (let index = start; index < text.length; index++) {
if (text.slice(index, 1) === ' ') {
newText = text.slice(start, index - start);
}
}
return +newText;
}
如果用戶將輸入此值“ employee#56 cv”,則需要獲得此輸出56
分配給newText
之后,循環將繼續,是的。 如果要在此時停止它,請使用break
:
newText = text.slice(start, index - start);
break;
但是您也可以通過再次使用indexOf
完全避免循環:
readNumber(text: string): number {
const start = text.indexOf('#') + 1;
if (start === -1) {
return 0; // Or whatever you should return when there's no # character
}
const end = text.indexOf(' ', start);
if (end === -1) {
end = text.length;
}
return +text.substring(start, end);
}
或正則表達式:
readNumber(text: string): number {
const match = /[^#]*#(\d+)/.exec(text);
if (!match) {
return 0; // Or whatever you should return when there's no # character
}
return +match[1];
}
這與您的示例稍有不同,因為它不查找空格,而只是查找數字。 要使用空格代替:
readNumber(text: string): number {
const match = /[^#]*#([^ ]*)(?: |$)/.exec(text);
if (!match) {
return 0; // Or whatever you should return when there's no # character
}
return +match[1];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.