首页 > 解决方案 > 添加满足特定条件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'

在排序时,我不能满足连续的顺序。我哪里错了?

标签: javascriptecmascript-6

解决方案


尝试这个:

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});


推荐阅读