javascript - 添加满足特定条件javascript的值
问题描述
我有一个字符串数组array_strings,我想从列表中获取x 个连续值的最大长度并返回一个字符串。我已经尝试过使用此代码,但是它不起作用。
var myArr = ['we', 'make', 'the', 'best', 'dishes', 'in', 'cooking', 'class'];
x = 2;
function myFunc(array_strings, x) {
// your code
let val = '',
y = 0;
array_strings.sort((a, b) => {
return a.length < b.length
});
if (array_strings.length > 0) {
while (x) {
val += array_strings[y];
y++;
x--;
}
}
return val;
}
console.log(myFunc(myArr, x))
// expected output 'cookingclass'
在排序时,我不能满足连续的顺序。我哪里错了?
解决方案
尝试这个:
arr = ['we', 'make', 'the', 'best', 'dishes', 'in', 'cooking', 'class']
x = 2
var sorting = function (array_strings, items) {
// your code
let val = '', y = 0;
const sort = array_strings.sort((a, b) => a.length < b.length);
console.log({sort});
if (arr.length > 0){
while (items){
val += array_strings[y];
y++;
items--;
}
}
return val;
}
var s = sorting(arr,x);
console.log({s});
推荐阅读
- reactjs - Bootstrap 4 在 Reactjs 中的按钮上加载 Spinner
- ios - Xamarin Forms Webview html 视频不在 iOS 设备上播放
- leaflet - 关于将geojson数据加载到传单的问题
- c++ - 这是一个旧的 C++ 风格的构造函数吗?
- excel - Power Query 中超过 24 小时的时间字段求和
- java - Axon - 事件处理程序拦截器配置
- python - python string.format,保留未使用/过度使用的键
- python - 有没有办法我可以用函数改变pygame中许多形状的颜色
- r - r-如何在使用 dplyr 的自定义函数上使用迭代
- python - Python 脚本不通过调用实用程序来处理 lftp 和 sftp