JavaScript自动逗号

JavaScript automatic comma

在我的程序中,用户输入了 0 到 8 之间的值。

例如:如果用户想输入“3,4”,他只需要写“34”。程序最终会将逗号放入,但我不知道该怎么做。

所以:

这是我尝试过的方法,但它当然会接受“34”作为整数:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

我也尝试过拆分输入,但是当用户输入像 3 这样的整数时,它就不再起作用了。

这个问题没有更深层次的意义,只是为了让用户输入更快。

正则表达式在这里有点矫枉过正,不是吗?

function numberWithCommas(x) {
  return x < 10 ? x.toString() : x.toString().split('').join(',');
}

你应该:

  1. 将输入的数字转换为字符串(toString);
  2. 将每个字符之间的字符串拆分成一个数组(split);
  3. 加入这个数组的元素,用,join)分隔。

这是完整的代码:

function numberWithCommas(x) {
    return x.toString().split("").join(",");
}