javascript lodashを使って数値に変換する
- 作成日 2022.02.15
- 更新日 2022.05.17
- 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>
数値に変換
数値に変換するには、「_.parseInt」を使用します。
'use strict';
console.log(
_.parseInt("10.11")
// 10
);
console.log(
_.parseInt("001")
// 1
);
console.log(
_.parseInt("0x10")
// 100
);
console.log(
_.parseInt("100年後")
// 100
);
console.log(
_.parseInt("百")
// NaN
);
実行結果を確認すると、変換されていることが確認できます。
サンプルコード
以下は、
「実行」ボタンをクリックして、ランダムに生成した2文字の16進数表記の文字列を、16進数に変換した結果を表示するサンプルコードとなります。
※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 = () => {
let str = "abcdef1234567890";
let randstr = '';
for (let i = 0; i < 2; i++) {
randstr += str[~~(Math.random() * str.length)];
}
str = "mebee"
foo1.textContent = str
foo2.textContent = randstr
bar.textContent = _.parseInt(randstr,16) // 16進数で計算
}
window.onload = () => {
btn.onclick = () => { hoge() }
}
</script>
<body>
<div class="container mx-auto my-56 w-1/3 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 id="foo1" class="font-semibold text-red-500 text-lg mr-auto">変換前</h1>
<h1 id="foo2" class="font-semibold text-red-500 text-lg mr-auto">挿入する文字列</h1>
<h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto">実行結果</h1>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-300 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-300 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、結果が表示されていることが確認できます。
-
前の記事
osquery メモリの状態を抽出する 2022.02.14
-
次の記事
python PySimpleGUIのTableに値を入れる 2022.02.15
コメントを書く