javascript - 在Javascript中创建一波字符串
问题描述
我似乎无法弄清楚如何从 Javascript 中的字符串发出波浪。
规则:
- 输入将始终是小写字符串。
- 忽略空格。
预期结果:
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; }
推荐阅读
- c# - 使用内置扫描仪作为 WIA 扫描仪计数打印机的方法
- java - Gradle - 使用带有闭包作为参数的插件方法的语法错误
- audio - FFmpeg Decklink 播放音频 PCM
- php - 验证 JSON 请求是一个数组,而不是一个对象
- docker - Elasticsearch docker容器占用了我所有的磁盘空间,找不到在哪里
- bash - 使用 Markdown.pl 批量转换 Markdown 文件
- python - unet 生成灰色预测图像
- python - Python Set_Blob_Metadata 和自身位置参数
- javascript - 通过选中复选框计算总价
- python - 如何在 Pandas DataFrame 中制作大写字母?