【问题标题】:JS function startsWith fails to give correct output.What is code smell in my code?JS 函数startsWith 无法提供正确的输出。我的代码中有什么代码异味?
【发布时间】:2021-08-24 13:31:39
【问题描述】:

我已经编写了这段代码来根据用户输入对列表进行排序,但是如果用户添加了一个在输入之间包含空格的输入,则以下代码无法获取输出,我需要进行哪些更改才能获得正确的输出?我不想删除字符之间的空格。 例如:用户输入是“Man santra”,那么它应该对“Man”列表进行排序

 var users = [{
    name: 'Devgad Mango'
  },
  {
    name: 'Mantra santra'
  },
  {
    name: 'Prag Mango'
  },
  {
    name: 'Pirate aam Mango'
  }, {
    name: 'Mango raw'
  },
];

function search(input) {
  const matches = [];
  const remeinder = [];
  users.forEach(user => {
    user.name.startsWith(input) ?
      matches.push(user) :
      remeinder.push(user);
  });
  console.log(matches, remeinder)

  // now we sort the matches

  matches.sort((a, b) => {
    const aa = a.name.toLowerCase();
    const bb = b.name.toLowerCase();
    if (aa < bb) {
      return -1;
    }
    if (aa > bb) {
      return 1;
    }
    return 0;
  });

  console.log(matches);
  // now we want to push the remeinders to the end of the sorted array.


  matches.push(...remeinder);

  console.log(matches);
  console.log(input);
}
const str = "*-*+&^%$#@!/\Man santra*";
var output = (str.replace(/[\/\\#@^!,+()&$~%.'":;*?`<>{}-]/g, ""));


search(output);

【问题讨论】:

  • 可能是因为user.name.startsWith(input),试试user.name.includes(input)
  • 您是指input.includes(user.name) 还是input.startsWith(user.name) 而不是user.name.startsWith(input)

标签: javascript json sorting compare string-comparison


【解决方案1】:

您必须使用 user.name.includes() 来检查变量中是否存在名称。然后你不必删除空格。您只需在搜索函数中传递输入,它就会返回包含该单词的匹配项。

var users = [{
    name: 'Devgad Mango'
  },
  {
    name: 'Mantra santra'
  },
  {
    name: 'Prag Mango'
  },
  {
    name: 'Pirate aam Mango'
  },
  {
    name: 'Mango raw'
  },
];

function search(input) {
  const matches = [];
  const remeinder = [];
  users.forEach(user => {
    user.name.includes(input) ?
      matches.push(user) :
      remeinder.push(user);
  });
  
  // now we sort the matches
  matches.sort((a, b) => {
    const aa = a.name.toLowerCase();
    const bb = b.name.toLowerCase();
    if (aa < bb) {
      return -1;
    }
    if (aa > bb) {
      return 1;
    }
    return 0;
  });

  console.log(matches);
  // now we want to push the remeinders to the end of the sorted array.
  matches.push(...remeinder);
  console.log(matches);
}
const str = "Mango";
search(str);

【讨论】:

  • 这里我的第一个要求是将结果排序为搜索值。即当你搜索“芒果”时,它应该用芒果对结果进行排序,这就是我使用startswith()函数的原因
  • 如果您看到代码排序功能正在处理名称,而不是搜索值。如果您实际上可以看到输出,则它是按字母顺序排列的。如果您想根据输入对其进行排序,您能否解释或举例说明输出的外观?
猜你喜欢
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2016-05-05
  • 1970-01-01
相关资源
最近更新 更多