📜  重复一个字符串 重复一个字符串 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:04:03.399000             🧑  作者: Mango

代码示例2
// Repeat a String Repeat a String

// Repeat a given string str (first argument) for num times (second argument).
// Return an empty string if num is not a positive number. For the purpose of this challenge, do not use the built-in .repeat() method.

function repeatStringNumTimes(str, num) {
    if (num < 0) return '';
    let result = '';
    for (let i = 0; i <= num - 1; i++) {
        result += str;
    }
    return result;
}

repeatStringNumTimes('abc', 3);

// OR

function repeatStringNumTimes(str, num) {
    var accumulatedStr = '';

    while (num > 0) {
        accumulatedStr += str;
        num--;
    }

    return accumulatedStr;
}

// OR

function repeatStringNumTimes(str, num) {
    if (num < 1) {
        return '';
    } else {
        return str + repeatStringNumTimes(str, num - 1);
    }
}

// OR

// my favourite
function repeatStringNumTimes(str, num) {
    return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}