我似乎无法弄清楚如何用Javascript中的字符串产生波浪。
规则:
预期结果:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]
wave ("") => []
Run Code Online (Sandbox Code Playgroud)
据我所知。当前的代码会给我一个答案["hello", "hello", "hello", "hello", "hello"]
。我正在考虑使用第二个for循环并以某种方式将每个新字母大写,但是我很困惑。如果答案可以避免在loop内部使用loop,我也将不胜感激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");
Run Code Online (Sandbox Code Playgroud)
您可以采用外循环来访问字符,如果找到非空格字符,请在此位置创建一个大写字母的新字符串。
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("")); // []
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
399 次 |
最近记录: |