首页 > 解决方案 > 在Javascript中创建一波字符串

问题描述

我似乎无法弄清楚如何从 Javascript 中的字符串发出波浪。

规则:

  1. 输入将始终是小写字符串。
  2. 忽略空格。

预期结果:

wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]

wave ("") => []

这是我得到的。当前代码会给我一个答案["hello", "hello", "hello", "hello", "hello"]。我正在考虑使用第二个 for 循环并以某种方式将每个新字母大写,但我很难过。如果答案会避免在循环内使用循环,我也将不胜感激O(n^2)。因为BIG O 可扩展性

const wave = (str) => {
    if(typeof str === 'string' && str === str.toLowerCase()){
       for (let index = 0; index < str.length; index++) {
        array.push(str);
    }
    for (let index = 0; index < str.length; index++) {
            console.log(array);   
    }
    }else{
        alert(`${str} is either not a string or not lowercase`);
    }
}
wave("hello");

标签: javascriptarrays

解决方案


您可以使用外部循环来访问字符,如果找到非空格字符,则在此位置创建一个带有大写字母的新字符串。

function wave(string) {
    var result = [],
        i;

    for (i = 0; i < string.length; i++) {
        if (string[i] === ' ') continue;
        result.push(Array.from(string, (c, j) => i === j ? c.toUpperCase() : c).join(''));
    }
    return result;
}

console.log(wave("hello"));   // ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
console.log(wave(" h e y ")); // [" H e y ", " h E y ", " h e Y "]
console.log(wave(""));        // []
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读