我需要编写一个将句子作为输入并输出排序后的句子的函数。并有两个条件:
单词的每个字符应按字母顺序排列
单词应根据字符数升序排列
注意:-单词只能包含小写字母
示例:
输入str =“她和他一起住在一个小公寓里”
输出=“在他身上,他击中了eilsv allms aaemnprtt”
这是我的代码。
function makeAlphabetSentenceSort(str) {
var sens = str.split(' ');
sens.sort(function(a, b) {
return a.length - b.length;
console.log(sens);
});
function alphaSort(b) {
var x = b.split("");
console.log(x.sort().join(""));
}
for (var i = 0; i <= sens.length - 1; i++) {
console.log(alphaSort(sens[i]));
}
}
console.log(makeAlphabetSentenceSort("she lives with him in a small enter code hereapartment"));
我对如何解决这个问题感到困惑。有什么建议吗?
答案 0 :(得分:1)
看来您的代码大都可以使用。通过将console.log(x.sort().join(""));
替换为return x.sort().join("");
我还必须删除console.log(alphaSort(sens[i]));
,以便将循环输出存储在名为output
的临时变量中,然后将整个循环输出作为字符串返回。
function makeAlphabetSentenceSort(str) {
var sens = str.split(' ');
sens.sort(function(a, b){
return a.length - b.length;
});
function alphaSort(b){
var x = b.split("");
return x.sort().join("");
}
var output = "";
for(var i = 0; i <= sens.length - 1; i++){
output += alphaSort(sens[i]) + " ";
}
return output.trim();
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));
出于可读性考虑,我还将代码重写如下:
let
关键字而不是var
关键字来实例化output
变量。output
变量(因为这是JS真正起作用的方式)
function makeAlphabetSentenceSort(str) {
let output = "";
// Sort the initial sentence by words alphabetically.
var sens = str.split(' ');
sens.sort(function(a, b){
return a.length - b.length;
});
for(var i = 0; i <= sens.length - 1; i++){
// Split each word into single characters. Sort the characters and
// join them back as a single string.
output += sens[i].split("").sort().join("");
// Because we want the response to look like a sentence.
output += " ";
}
return output.trim();
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));