JavaScript 字符串中的锯齿状模式?
javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/17 1:16:17
我们需要编写一个函数来读取字符串并将字符串中的奇数索引字符转换为大写,将偶数索引字符转换为小写并返回一个新字符串。
执行相同操作的完整代码如下 −
const text = 'Hello world, it is so nice to be alive.';
const changeCase = (str) => {
const newStr = str
.split("")
.map((word, index) => {
if(index % 2 === 0){
return word.toLowerCase();
}else{
return word.toUpperCase();
}
})
.join("");
return newStr;
};
console.log(changeCase(text));
代码将字符串转换为数组,映射每个单词并根据其索引将其转换为大写或小写。
最后,它将数组转换回字符串并返回它。
以下是控制台上的输出 −
hElLo wOrLd, It iS So nIcE To bE AlIvE.
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

