2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptによるカンマ区切りプログラム(配列の挿入を使う方法)

Posted at

JavaScriptによるカンマ区切りのプログラムです。
今回はカンマ区切りの関数(Number(value).toLocaleString)は使用禁止として作成しました。




process.stdin.resume();
process.stdin.setEncoding('utf8');

var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
  //数字変数
  var num = lines[0];
  //数値を配列にする
  var num1 = num.split('');
  //配列の長さ
  const leng = num1.length;
  //挿入する配列の位置の変数定義
  var target = leng;
  //カンマ文字の定義
  const msg = ",";
  
  while(target > 3){
      target =target - 3;
      //カンマを指定した位置に挿入する
      num1.splice(target,0,msg);
  }
  const leng2 = num1.length;
  //答えの文字列の定義
  let ans = "";
  //配列から文字列を代入する
  for(let i=0;i<leng2;i++){
    ans = ans + num1[i];
  }
  //答えを出力する
  console.log(ans);
});

以上のような実装でできます。

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?