【问题标题】:comparing IDs generated from uuid npm package比较从 uuid npm 包生成的 ID
【发布时间】:2020-04-26 02:24:24
【问题描述】:

我的函数应该删除一个食谱。

所以我只在 ID 不等于作为参数传递的 ID 时过滤所有食谱

(如果在数组中找到 ID,我们应该只删除配方)

ID 是使用包 uuid 生成的(v4 方法)

const removeRecipe = (id) => {
  const recipes = loadRecipes();
  const recipesToKeep = recipes.filter((recipe) => {
    return recipe.id !== id;
  });

  if (recipes.legth > recipesToKeep.legth) {
    console.log(chalk.green.inverse('Recipe Removed'));
    saveRecipes(recipesToKeep);
  } else {
    console.log(chalk.red.inverse('Recipe not found'));
  }
};

问题在于,即使 ID 的值和类型(字符串)相等,并且过滤器函数应该忽略配方,该函数仍然返回 false

所以 "c3a76b5b-bc36-4e87-8e2c-229211ca265d" === "c3a76b5b-bc36-4e87-8e2c-229211ca265d" 为真,不应成为过滤数组的一部分,但它被评估为假

【问题讨论】:

  • 请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 了解如何提高问题的质量。然后edit你的问题包含你的源代码作为minimal reproducible example,它可以被其他人编译和测试。
  • 在你保存任何东西之前你确定这不是拼写错误?即,检查您的假设,并在问题中包含验证。

标签: javascript uuid


【解决方案1】:

我有一个错字

if (recipes.legth > recipesToKeep.legth) {

我必须是

if (recipes.length > recipesToKeep.length) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2020-04-22
    • 2014-05-13
    • 2019-12-10
    • 2016-02-25
    • 2016-07-31
    • 2015-06-30
    • 1970-01-01
    相关资源
    最近更新 更多