javascript 配列をカンマ区切りの文字列に変換する
- 2020.11.11
- javascript
- javascript

javascriptで、joinを使用して、配列をカンマ区切りの文字列に変換するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
join使い方
joinを使用すると、配列をカンマ区切りの文字列に変換することが可能です。
const arr = ["a","b","c"];
console.log(
arr.join(',') // a,b,c
);
サンプルコード
以下は、
「実行」ボタンをクリックすると、ランダムに生成した配列をカンマ区切りの文字列としてフロントに表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
.main {
margin: 0 auto;
margin-top: 200px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 30px;
}
</style>
<script>
function hoge() {
// ランダムな3個の整数1桁の配列を生成
const arr = Array(3).fill().map(x => ~~(Math.random() * 10));
// 生成した配列をカンマ区切りで表示
result.innerHTML = arr.join(',');
}
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
}
</script>
<body>
<div class="main container">
<h2><span id="result" class="badge bg-info">カンマ区切りの文字列を表示</span></h2>
<div class="row">
<button id="btn" type="button" class="btn btn-warning">
実行
</button>
</div>
</div>
</body>
</html>
カンマ区切りの文字列に変換されて表示されていることが確認できます。

-
前の記事
C# List(リスト)内にある値の個数を取得する 2020.11.10
-
次の記事
Rails renderメソッドを使用してjsonを返す 2020.11.11
コメントを書く