javascript - 在 Javascript 中创建一波字符串

标签 javascript arrays

我似乎无法弄清楚如何从 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");

最佳答案

您可以采用外循环来访问字符,如果找到非空格字符,则在该位置创建一个包含大写字母的新字符串。

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; }

关于javascript - 在 Javascript 中创建一波字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54983179/

相关文章:

javascript - Jquery - 隐藏单选按钮 - 但使图像可点击以显示更大的图像

javascript - 如何通过在 AngularJS 中链接 http 调用来构建对象数组?

C++数组选择平方数并制作新 vector

PHP:从 xml 生成数组时存在非法偏移类型

c - 为字符缓冲区分配可变长度数组

javascript - Lodash _.setWith 自定义路径

javascript - 从两个触发器切换 jquery

javascript - IIS URL 重写 CSS url() 值的问题

C++查找二维数组中两点之间的距离

C结构指向结构数组的指针,来自结构