おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第104弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Basic JavaScriptの中の、
Use the parseInt Function
です。
さっそく見ていきましょう。
まずは本文から。
The
parseInt()
function parses a string and returns an integer. Here’s an example:var a = parseInt("007");
The above function converts the string “007” to an integer 7. If the first character in the string can’t be converted into a number, then it returnsNaN
.Use parseInt()
in theconvertToInteger
function so it converts the input stringstr
into an integer, and returns it.
解説していきます。
今回はparseInt関数についてです。
この関数は文字列として入力された数字を整数の数値として変換する関数です。
例えば、
var a = parseInt( “007”);
上記の関数は、文字列 “007”を整数7に変換します。
文字列の最初の文字を数値に変換できない場合、NaNを返します。
因みに少数は小数点以下が切り捨てされます。
では課題を見てみましょう。
convertToInteger関数でparseInt()を使用して、入力文字列strを整数に変換して返せ。という課題です。
簡単ですね。
引数の値をparseInt関数の中にいれてあげればいいだけです。
答えはこうです。
function convertToInteger(str) {
return parseInt(str);
}
という事で今回はperseInt関数について学びました。
では次回!