javascript lodashを使って整数に変換する
- 作成日 2021.11.25
- 更新日 2022.05.10
- javascript lodash
- javascript, lodash

javascriptで、lodashを使って整数に変換するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- lodash 4.17.21
- ブラウザ chrome 91.0.4472.77
lodash使用
こちらのサイトから最新版を確認して、CDN版を使用してます。
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

整数に変換
整数に変換するには、「_.toInteger」を使用します。
'use strict';
console.log(
_.toInteger(1) // 1
)
console.log(
_.toInteger(1.1) // 1
)
console.log(
_.toInteger(-1.1) // -1
)
console.log(
_.toInteger('1.1') // 1
)
console.log(
_.toInteger(Number.MIN_VALUE) // 0
)
console.log(
_.toInteger(Number.MAX_VALUE) // 1.7976931348623157e+308
)
console.log(
_.toInteger(null) // 0
)
console.log(
_.toInteger(Infinity) // 1.7976931348623157e+308
)
console.log(
_.toInteger(undefined) // 0
)
console.log(
_.toInteger(true) // 1
)
console.log(
_.toInteger(false) // 0
)
console.log(
_.toInteger(NaN) // 0
)
console.log(
_.toInteger([5]) // 5
)
console.log(
_.toInteger([1,2]) // 0
)
console.log(
_.toInteger({ 'a': 5 }) // 0
)
実行結果を確認すると、整数に変換されていることが確認できます。

サンプルコード
以下は、
「実行」ボタンをクリックして、ランダムに生成した少数を整数に変換した結果を表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<script>
const hoge = () => {
const num = Math.random() * 10
foo.innerHTML = num
bar.innerHTML = _.toInteger(num)
}
const disp = (arr, id) => {
let text = [];
arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
btn.onclick = () => { hoge() }
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 id="foo" class="font-semibold text-red-700 text-lg mr-auto">変換前</h1>
<h1 id="bar" class="font-semibold text-red-700 text-lg mr-auto">実行結果</h1>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-red-300 text-red-700 font-semibold hover:text-white py-2 px-4 border border-red-300 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、変換した結果が表示されていることが確認できます。

-
前の記事
rails6 form_withを使ってpostする 2021.11.24
-
次の記事
php 作成した配列のインデックス番号の順番について 2021.11.25
コメントを書く