使用 find 语句设置标志值
Setting values of flag with find statement
我正在开发 angular 应用程序。在我的代码中,我必须从数组中找到一个元素并设置标志的值。我的代码如下
myId = this.Names.find(id => id === '1');
因此,我正在从 Names 数组中检查 id。如果 id 为 1,我需要将标志 myFlag 设置为 true。我知道我可以在此之后使用 if else 语句。但是我想更有效地做,而不是 if else。有什么方法可以直接从 find 语句设置 myFlag。
如果找不到任何东西,find()
将 return undefined
,所以你可以这样做:
const myFlag = !myId; // Sets to true if nothing is found
const myFlag = !!myId; // Sets to false if nothing is found
您也可以查看 some(),但这不是 return 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
我正在开发 angular 应用程序。在我的代码中,我必须从数组中找到一个元素并设置标志的值。我的代码如下
myId = this.Names.find(id => id === '1');
因此,我正在从 Names 数组中检查 id。如果 id 为 1,我需要将标志 myFlag 设置为 true。我知道我可以在此之后使用 if else 语句。但是我想更有效地做,而不是 if else。有什么方法可以直接从 find 语句设置 myFlag。
find()
将 return undefined
,所以你可以这样做:
const myFlag = !myId; // Sets to true if nothing is found
const myFlag = !!myId; // Sets to false if nothing is found
您也可以查看 some(),但这不是 return 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