以下是使用JavaScript实现的代码:

function addCommas(num) {
  var numStr = num.toString(); // 将数字转换为字符串
  var result = ''; // 存储结果的变量
  var count = 0; // 计数器,用于每隔三个字符插入逗号
  
  // 从字符串末尾开始循环
  for (var i = numStr.length - 1; i >= 0; i--) {
    result = numStr[i] + result; // 将当前字符加入结果字符串的开头
    
    // 如果当前字符不是数字,则跳过
    if (isNaN(numStr[i])) {
      continue;
    }
    
    count++; // 计数器自增
    
    // 每隔三个字符插入逗号
    if (count % 3 === 0 && i !== 0) {
      result = ',' + result;
    }
  }
  
  return result;
}

// 示例:
var num = 1234567890;
var result = addCommas(num);
console.log(result); // 输出 "1,234,567,890"

在这个函数中,我们首先将数字转换为字符串,然后从字符串的末尾开始循环。在循环中,我们将当前字符加入结果字符串的开头,并且每隔三个字符插入一个逗号。为了实现这个功能,我们使用了一个计数器来记录我们已经遍历了多少个数字字符。如果当前字符不是数字,则跳过。最后,我们将结果字符串返回。

用js给一串数字从末尾起每三个字符增加一个

原文地址: https://www.cveoy.top/t/topic/bu7J 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录