按升序排列字符串中的单词 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/12 15:08:17
假设,我们需要编写一个 JavaScript 函数,该函数接受一个字符串并返回一个新字符串,其中单词根据其长度的增加重新排列。
示例
以下是代码 −
const str = 'This is a sample string only';
const arrangeByLength = str => {
const strArr = str.split(' ');
const sorted = strArr.sort((a, b) => {
return a.length - b.length;
});
return sorted.join(' ');
};
console.log(arrangeByLength(str));
输出
以下是控制台中的输出 −
a is This only sample string
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

