Mug*_*g84 3 javascript for-loop splice array-splice
我已经在这个函数上工作了一段时间,但我不明白为什么即使我使用 .splice() 我也没有得到一个修改过的数组。我提供了开始更改数组“i”的索引、要删除的元素数“1”和要添加的元素“str[i]”。
function wave(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
if ((/[a-z]/ig).test(str[i])) {
let st = str.split("").splice(i, 1 , str[i].toUpperCase());
result.push(st);
}
}
return result;
}
console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];Run Code Online (Sandbox Code Playgroud)
Array#splice返回删除的项目。您需要保留数组 - 并删除并添加新项目。
正则表达式不需要用括号包裹来访问RegExp#test方法。
在推送到数组之前,您需要Array#join获取单个字符串。
function wave(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
if (/[a-z]/ig.test(str[i])) {
let st = str.split("");
st.splice(i, 1, str[i].toUpperCase());
result.push(st.join(''));
}
}
return result;
}
console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |