【问题标题】:Setting values of flag with find statement使用 find 语句设置标志值
【发布时间】:2020-08-25 05:02:35
【问题描述】:

我正在开发一个 Angular 应用程序。在我的代码中,我必须从数组中找到一个元素并设置标志的值。我的代码如下

 myId = this.Names.find(id => id === '1');

所以,我从 Names 数组中检查 id。如果 id 为 1,我需要将标志 myFlag 设置为 true。我知道我可以在此之后使用 if else 语句。但不是 if else,我想更有效地做到这一点。有什么方法可以直接从 find 语句中设置 myFlag。

【问题讨论】:

  • 一般情况下,您可以使用.some(),这将返回您要查找的布尔值。 const myFlag = this.Names.some(id => id === '1');。在这种情况下,您可以简单地使用.includes()const myFlag = this.Names.includes('1');

标签: javascript angular typescript angular8


【解决方案1】:

find() 如果找不到任何东西,将返回undefined,所以你可以这样做:

const myFlag = !myId; // Sets to true if nothing is found
const myFlag = !!myId; // Sets to false if nothing is found

您也可以查看some(),但这不会返回 id:

const myFlag = this.Names.some(id => id === '1'); // If it finds an id with 1, sets to true. Otherwise, false

这些用于对象数组,所以如果你的数组只有字符串,你可以使用includes()

const myFlag = this.Names.includes('1'); // If it finds an id with 1, sets to true. Otherwise, false

【讨论】:

  • 我的 vscode 没有显示某些选项。我怎样才能得到它?
  • 因为我的模型名称是任何类型。当我按名称排列时? : [] ,它运行代码但给出错误 A tuple type element list cannot be empty.
  • 试试Name?: string[](所以是字符串数组)。或Name?: any[](任何东西的数组)
猜你喜欢
  • 2014-11-25
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
相关资源
最近更新 更多