繁体   English   中英

如何从JavaScript的for循环内部获取价值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM