JavaScript助手| startsWith()不是函数

时间:2019-01-20 00:55:44

标签: javascript ecmascript-6

我需要编写一个 helper函数,该函数遍历对象数组并过滤所有符合既定条件的名称。就我而言,所有以Zach

开头的名字

数组示例:

const users = [
  {
    firstName: "Zach",
    id: 1,
    lastName: "Volsk"
  },
  {
    firstName: "Surly",
    id: 2,
    lastName: "Furious"
  },

  {
    firstName: "Zach",
    id: 3,
    lastName: "Tee"
  },
  {
    firstName: "Eve",
    id: 4,
    lastName: "Zelda"
  },

  {
    firstName: "Zachary",
    id: 5,
    lastName: "Toys"
  }
];

我可以使用过滤器检索所需结果并直接映射,即:

const filterZach = users
  .filter(user => user.firstName.startsWith("Zach"))
  .map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join(""); // get rid of comas

期望的结果:Zach Volsk, Zach Tee, Zachary Toys

但是,当我尝试将该功能抽象为辅助方法时,可以在代码的其他地方使用它: 即:

// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.startsWith(str));
}

我收到一条错误消息: i.startsWith不是函数

const filterZach = filteredNames(users, "Zach") // i.startsWith is not a function
const renderZach = filterZach.map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join("");

问题:能否请您帮助解决此问题的原因,向我展示使用助手功能实现目标的替代方法?

我还没有嫁给startsWith( )方法,我很想学习其他解决方法。减少也许?

这是一个code sandbox

1 个答案:

答案 0 :(得分:5)

filteredNames内,arr.filter(i中,i是一个对象,而不是字符串,并且对象没有startsWith方法。改为引用对象的firstName,然后在其上调用startsWith

// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}

const users = [
  {
    firstName: "Zach",
    id: 1,
    lastName: "Volsk"
  },
  {
    firstName: "Surly",
    id: 2,
    lastName: "Furious"
  },

  {
    firstName: "Zach",
    id: 4,
    lastName: "Tee"
  },
  {
    firstName: "Eve",
    id: 5,
    lastName: "Zelda"
  },

  {
    firstName: "Zachary",
    id: 6,
    lastName: "Toys"
  }
];
// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}
const filterZach = filteredNames(users, "Zach") // i.startsWith is not a function
const renderZach = filterZach.map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join("");
document.body.innerHTML += renderZach;

要使动态属性名称调用startsWith,请将该属性名称传递给filteredNames,例如

function filteredNames(arr, str, prop) {
  return arr.filter(i => i[prop].startsWith(str));
}