ES6:使用模板文字创建字符串 - Freecodecamp

问题描述


我尝试解决以下问题,通过了 4 个条件中的 3 个。我无法在下面的代码中找到更多错误。但它仍然说“failuresList 应该是一个包含结果失败消息的数组。”

链接
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals

问题:
使用带有反引号的模板文字语法来创建一个列表元素 (li) 字符串数组。每个列表元素的文本应该是结果对象上失败属性的数组元素之一,并且具有值为 text-warning 的类属性。 makeList 函数应返回列表项字符串数组。

使用迭代器方法(任何类型的循环)来获得所需的输出

[
  '<li class="text-warning">no-var</li>','<li class="text-warning">var-on-top</li>','<li class="text-warning">linebreak</li>'
]
  1. 未通过:failuresList 应该是一个包含结果失败消息的数组。

  2. Passed : failuresList 应该等于指定的输出

  3. Passed :应使用模板字符串和表达式插值。

  4. 通过:应该使用迭代器。

以下是我目前的代码

const result = {
  success: ["max-length","no-amd","prefer-arrow-functions"],failure: ["no-var","var-on-top","linebreak"],skipped: ["id-blacklist","no-dup-keys"]
};

function makeList(arr) {
  "use strict";
 
 
  // Only change code below this line
  const resultdisplayArray = (arr) =>{
    let failure = [];
   for (let element of arr) {
      failure.push(`<li class="text-warning">${element}</li>`);
    }
  
    return failure;
    
  };
  // Only change code above this line

  return resultdisplayArray(arr);
}

const resultdisplayArray = makeList(result.failure);
console.log(resultdisplayArray);

解决方法

您不需要 resultDisplayArray 函数中的额外 makeList 函数。只需循环遍历数组!

function makeList(arr) {
  // Only change code below this line
  const failureItems = [];
  for (let element of arr) {
      failureItems.push(`<li class="text-warning">${element}</li>`);
  }
  // Only change code above this line
  return failureItems;
}
,

这里最好使用 map 方法。

const result = {
  success: ["max-length","no-amd","prefer-arrow-functions"],failure: ["no-var","var-on-top","linebreak"],skipped: ["no-extra-semi","no-dup-keys"]
};
function makeList(arr) {
  // Only change code below this line
  const failureItems = result.failure.map(element => `<li class="text-warning">${element}</li>`);
  // Only change code above this line
  return failureItems;
}

const failuresList = makeList(result.failure);
,

因此,我将通过 2 种方式提及这些问题:如何修复您的代码,我将建议一种干净的方法来解决问题。

  1. 问题与代码的正确性无关,但事实上,您更改了正在检查的变量的名称。您应该将全局范围中的变量“failuresList”保留为保存结果数组的变量。但是,您将其更改为“resultDisplayArray”。 复制粘贴您的代码并仅更改名称,结果通过所有测试" (我指的是代码中最后一行之前的行)
  2. 您不应该使用内部函数“resultDisplayArray”包装数组创建。这就是“makeList”的用途,内部函数是多余的,因此不应该存在。
  3. 我会这样做:

const result = {
  success: ["max-length","no-dup-keys"]
};

function makeList(arr) {
  // Only change code below this line
  const failureItems = arr.map(curr => `<li class="text-warning">${curr}</li>`);
  // Only change code above this line

  return failureItems;
}

const failuresList = makeList(result.failure);
console.log(failuresList);