wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

JS基础测试37期:数值格式处理/单位换算 #28

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

题目:

image


我的回答:

第 1 题:

var backCode = '6222081812002934027';

// 方法1
var result = backCode.replace(/(\d{4})/g, '$1 ');
console.log(result);  // "6222 0818 1200 2934 027"

// 方法2
var result = backCode.split(/(\d{4})/).filter(s => !!s).join(' ');
console.log(result);  // "6222 0818 1200 2934 027"

第 2 题:

var numberCode = ‘5702375’;
var result = numberCode.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');  // 未考虑小数情况
console.log(result);  // "5,702,375"

第 3 题:

var filesize = 2837475;

function matchUnit(value) { 
  var sizeUnits = ['K', 'M', 'G'];
  var sizeRadix = 1024;

  if (value < sizeRadix) {
    return (value / sizeRadix).toFixed(1) + sizeUnits[0]
  }

  for (var i = sizeUnits.length - 1; i >= 0; i--) {
    var radix = Math.pow(sizeRadix, i + 1);
    if (value >= radix) {
      return (value / radix).toFixed(1) + sizeUnits[i]
    }
  }
}

console.log(matchUnit(filesize));  // 2.7M
console.log(matchUnit(100));  // 0.1K
console.log(matchUnit(10000));  // 9.8K
console.log(matchUnit(100000000));  // 95.4M
console.log(matchUnit(10000000000));  // 9.3G