我正在开发一款angular应用程序。在我的代码中,我必须从数组中找到一个元素并设置标志的值。我的代码如下
myId = this.Names.find(id => id === '1');
所以,我从Names数组中检查id。如果id是1,我需要将标志myFlag设置为true。我知道在这之后我可以使用if-else语句。但我想做的不是别的,而是更有效率。有没有什么方法可以直接从find语句中设置myFlag。
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