我正在在线学习ES 6,并且已经测试:


  实现findLargestString函数,该函数具有单个参数
  字符串(字符串数组),它将设置maximumString
  长度最大的字符串顶部定义的变量
  作为strings参数传入的字符串数组的值。


一开始我有方法:

let largestString;

function findLargestString(strings) {
    // set largestString to point to the
    // longest string found in the strings array passed in
}


所以我尝试了:

let largestString;

function findLargestString(strings) {
    let largestString = '';
    strings.forEach((string) => {
        if (string.length > largestString.length) {
            largestString = string;
        }
    });

    return largestString;
}


但这返回错误:

largestString should be set to the largest string passed in

Expected undefined to equal 'computers'.


我该怎么做?

最佳答案

您的代码对我来说似乎很好



let largestString;

function findLargestString(strings) {
  let largestString = '';
  strings.forEach((string) => {
    if (string.length > largestString.length) {
      largestString = string;
    }
  });

  return largestString;
}

var arr = new Array('', 'aa', 'test')
console.log(findLargestString(arr));

08-15 15:03