0

JavaScript parseInt() は、Java parseInt() と同じようには機能しないようです。

非常に簡単な例は次のとおりです。

document.write(parseInt(" 60 ") + "<br>");  //returns 60
document.write(parseInt("40 years") + "<br>");  //returns 40
document.write(parseInt("He was 40") + "<br>");  //returns NaN

1号線は大丈夫です。しかし、実際には「年」を整数に変換できないため、2行目でエラーが発生すると予想されます。JavaScript parseInt() は、文字列の最初の数文字が整数かどうかをチェックするだけだと思います。

では、文字列に非整数がある限り、NaN が返されることを確認するにはどうすればよいでしょうか?

4

5 に答える 5

4

parseInt は、整数を解析する際の柔軟性を考慮して設計されています。Number コンストラクターは余分な文字を使用すると柔軟性が低下しますが、整数以外も解析します (Alex に感謝します):

console.log(Number(" 60 "));  // 60
console.log(Number("40 years"));  // Nan
console.log(Number("He was 40"));  // NaN
console.log(Number("1.24"));  // 1.24

または、正規表現を使用します。

" 60 ".match(/^[0-9 ]+$/);  // [" 60 "]
" 60 or whatever".match(/^[0-9 ]+$/);  // null
"1.24".match(/^[0-9 ]+$/);  // null
于 2013-03-26T02:49:12.890 に答える
0

文字列に整数以外が含まれているかどうかを確認するには、正規表現を使用します。

function(myString) {
  if (myString.match(/^\d+$/) === null) {  // null if non-digits in string
    return NaN
  } else {
    return parseInt(myString.match(/^\d+$/))
  }
}
于 2013-03-26T02:51:25.263 に答える
0

次のような正規表現を使用します。

function parseIntStrict(stringValue) { 
    if ( /^[\d\s]+$/.test(stringValue) )  // allows for digits or whitespace
    {
        return parseInt(stringValue);
    }
    else
    {
        return NaN;
    }
}

于 2013-03-26T02:54:22.290 に答える
0

最も簡単な方法は、おそらく単項プラス演算子を使用することです。

var n = +str;

ただし、これは浮動小数点値も解析します。

于 2013-03-26T02:57:39.633 に答える
0

以下は、isIntegerすべての String オブジェクトに追加できる関数です。

// If the isInteger function isn't already defined
if (typeof String.prototype.isInteger == 'undefined') {

    // Returns false if any non-numeric characters (other than leading
    // or trailing whitespace, and a leading plus or minus sign) are found.
    //
    String.prototype.isInteger = function() {
        return !(this.replace(/^\s+|\s+$/g, '').replace(/^[-+]/, '').match(/\D/ ));
    }
}

'60'.isInteger()       // true
'-60'.isInteger()      // true (leading minus sign is okay)
'+60'.isInteger()      // true (leading plus sign is okay)
' 60 '.isInteger()     // true (whitespace at beginning or end is okay)

'a60'.isInteger()      // false (has alphabetic characters)
'60a'.isInteger()      // false (has alphabetic characters)
'6.0'.isInteger()      // false (has a decimal point)
' 60 40 '.isInteger()  // false (whitespace in the middle is not okay)
于 2013-03-26T03:01:50.260 に答える