代码优化oooooo

gzc
  • 69
function mosaicZero(var num) {
    //根据num拼接字符串zero,数字num是几字符串zero就有几个0.num取值范围0-16
    var zero = "";
    if (num == 0) zero = "0";
    if (num == 1) zero = "00";
    if (num == 2) zero = "000";
    if (num == 3) zero = "0000";
    if (num == 4) zero = "00000";
    if (num == 5) zero = "000000";
    if (num == 6) zero = "0000000";
    if (num == 7) zero = "00000000";
    if (num == 8) zero = "000000000";
    if (num == 9) zero = "0000000000";
    if (num == 10) zero = "00000000000";
    if (num == 11) zero = "000000000000";
    if (num == 12) zero = "0000000000000";
    if (num == 13) zero = "00000000000000";
    if (num == 14) zero = "000000000000000";
    if (num == 15) zero = "0000000000000000";
    if (num == 16) zero = "00000000000000000";
    return zero;
}
回复
阅读 2.3k
8 个回答
✓ 已被采纳
var num = 5;
var result = "00000000000000000".substr(0, num);

我去,最笨的办法 for 循环一次吧。。

var zero='';
function mosaicZero(num) {

for(var i=0;i<=num;i++){
    zero+='0';
}
return zero;

}

使用repeat方法:

function mosaicZero(num){
    if(num > -1 && num < 17){
        return "0".repeat(num + 1);
    }
    return "";
}
function mosaicZero(num){
  if(typeof num === 'number'){
    return new Array(num + 1).join('0');
  } 
  
  return '';
}

主要利用了Array.prototype.join可以在数组间插入指定的字符串,所以先构建一个包含num + 1个元素的数组(需要+1才能在数组间产生num个间隔)。

不知道你是不是只想得到0还是前面还有num,于是都写了,写的不好,轻喷

    function mosaicZero(num) {
        var zero = '';
        if (num < 16) {
            for (var i = 0; i < num; i++) {
                zero += '0' * num
            }
            zero = num.toString() + zero;
        }
        return zero;
    }

    console.log(mosaicZero(17))

    function mosaicZero(num) {
        var zero = '';
        if(num<16) {
            for(var i=0; i<num; i++) {
                zero += '0' * num
            }
        }
        return zero
    }
    console.log(mosaicZero(7));
return "0".repeat(num);

等下,例子里是不是多了一个,num返回num+1个0?

那么

return "0".repeat(num+1);

ES6

function mosaicZero (num){
    return new Array(num + 1).fill(0);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏