【问题标题】:Reversing an integer taken from event value: only works properly for the 1st event反转取自事件值的整数:仅适用于第一个事件
【发布时间】:2020-02-26 20:28:23
【问题描述】:

从 Angular 输入中反转一个数字。

这里是方法和属性:

reversedIntInput = "";

  reverseInt(event: any) {
    const inputString = (<HTMLInputElement>event.target).value;
    const parsed = parseInt(inputString);

    if (Number.isNaN(parsed) || inputString == "" || inputString === null) {
      this.reversedIntInput = "Nice try but this is not a number.";
    } else {
      this.reversedIntInput = inputString
        .split("")
        .reverse()
        .join("");
    }
  }

这里是html:

<label>Reverse an Integer</label>
<input type="text" class="form-control" (input)="reverseInt($event)">
<p>{{ reversedIntInput }}</p>

如果我在输入中输入“d”,它确实会显示“Nice try but this is not a number”。 如果我在输入中输入“45”,它确实会显示“54”。

但如果我输入“54ddd”,它只会将其反转为字符串,并在应该显示“Nice try but this is not a number”时显示“ddd45”。

这是为什么呢?我在控制台记录了inputStringparsed,并且当输入了一个字母但解析后没有时,inputString 会继续更新。

【问题讨论】:

  • 添加 keydown 事件,当被按下时在按下的键上取 ASCII 码,然后检查 asci 码是否 >= 48 &&

标签: javascript angular typescript


【解决方案1】:

只需检查 inputString 是否有值并且该值是一个数字,请参见:

if (inputString  && Number(inputString)) {
   this.reversedIntInput = reverse logic .....
} else {
  this.reversedIntInput = "Nice try but this is not a number.";
}

【讨论】:

    【解决方案2】:

    发生这种情况是因为parseInt 如果您传递一个以数字开头的字符串,则会返回一个有效的Number。它只是忽略了数字后面的内容:

    const inputString = '54ddd';
    const parsed = parseInt(inputString);
    
    console.log(parsed); // prints 54

    因此,在这种情况下,当您检查Number.isNaN(parsed) 时,它将返回false,因为54 是有效的Number

    您可以直接在您的字符串 (inputString) 上使用 isNaN 而不是 Number.isNaN,它会按照您的预期工作 (yes, Number.isNan and isNan are different functions):

    if (isNaN(inputString) || inputString == "" || inputString === null) {
    

    在不完全是数字的字符串上调用isNan时(即使它以1开头),它会返回true

    const inputString = '54ddd';
    
    console.log(isNaN(inputString)); // prints true

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 2018-06-26
      • 2019-07-24
      相关资源
      最近更新 更多