编写一个函数,该函数接受一个或多个单词的字符串,并返回相同的字符串,但所有五个或更多字母单词都反转了。传入的字符串将仅包含字母和空格。仅当存在多个单词时才包含空格。
function spinWords(string){
//splits string into words separated by a space
var splitStringArray = string.split(" ");
for (var i = 0; i < splitStringArray.length; i++) {
//if the word is more than 5 chars, reverse the word
if (splitStringArray[i].length >= 5) {
splitStringArray[i].split("").reverse().join("");
}
} //end for loop
//join the modified array
var joinString = splitStringArray.join(" ");
return joinString;
} //end function
console.log(spinWords("Hey fellow students"));
我无法反转5个或更多字符的单词。我试图首先将字符串拆分为字符串数组。然后,我尝试评估该数组中每个字符串的长度。如果单词的长度为5或更多,则我想拆分,反转和加入该单词。然后,我想加入数组并显示输出。
输出应为“ Hey wollef stneduts”。
答案 0 :(得分:3)
一切都正确,因为javascript中的字符串是不可变的,因此您需要分配回该值。只需更改行:
splitStringArray[i].split("").reverse().join("");
收件人
splitStringArray[i]=splitStringArray[i].split("").reverse().join("");
function spinWords(string){
//splits string into words separated by a space
var splitStringArray = string.split(" ");
for (var i = 0; i < splitStringArray.length; i++) {
//if the word is more than 5 chars, reverse the word
if (splitStringArray[i].length >= 5) {
splitStringArray[i]= splitStringArray[i].split("").reverse().join("");
}
} //end for loop
//join the modified array
var joinString = splitStringArray.join(" ");
return joinString;
} //end function
console.log(spinWords("Hey fellow students"));
答案 1 :(得分:0)
您尚未使用反向值更新数组。 只需循环分配即可
function spinWords(string){
//splits string into words separated by a space
var splitStringArray = string.split(" ");
for (var i = 0; i < splitStringArray.length; i++) {
//if the word is more than 5 chars, reverse the word
if (splitStringArray[i].length >= 5) {
splitStringArray[i]=splitStringArray[i].split("").reverse().join("");
}
} //end for loop
//join the modified array
var joinString = splitStringArray.join(" ");
return joinString;
} //end function
console.log(spinWords("Hey fellow students"));