【问题标题】:JavaScript function always return false even if a value is true即使值为 true,JavaScript 函数也总是返回 false
【发布时间】:2022-06-28 22:48:59
【问题描述】:

我有一个函数返回true 或false,但我看到的是这个函数总是返回false。

  const isLastImageAttachment = index => {
    const isLastImage =
      filteredImages.uuid === attachments[index].uuid;
    console.log(`isLastImage:`, isLastImage); // true
    return isLastImage ? true : false;
  };

  console.log('isLastImageAttachment()', isLastImageAttachment()); // false

isLastImage 返回true 或false 但isLastImageAttachment 总是返回false,即使isLastImage 是true。

这有什么问题?

尝试

我自己返回isLastImage。

  const isLastImageAttachment = index => {
    const isLastImage =
      filteredImages.uuid === attachments[index].uuid;
    console.log(`isLastImage:`, isLastImage); // true
    return isLastImage;
  };

但是isLastImageAttachment 返回false。

当然只回true,我有回true

  const isLastImageAttachment = index => {
    return true;
  };

【问题讨论】:

  • 不可能按现状说。这段代码无论如何都不会运行,因为你没有传入索引,所以attachments[undefined] 会抛出一个错误。另外,请注意isTrue ? true : false 是多余的。你可以return isLastImage。
  • 请注意,return isLastImage ? true : false; 与 return isLastImage; 完全相同,此外,我们不知道 filteredImages 或 attachments 是什么。
  • @AleksandrH:attchments[undefined] 不会扔,但 undefined.uuid 会。
  • console.log('isLastImageAttachment()', isLastImageAttachment()); // false 你没有将index 传递给函数...

标签: javascript reactjs


【解决方案1】:

你能在你的函数中只返回 isLastImmage 本身吗? 像这样:

const isLastImageAttachment = index => {
const isLastImage =
  filteredImages.uuid === attachments[index].uuid;
console.log(`isLastImage:`, isLastImage); // true
return isLastImage;

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多