简体   繁体   English

结合 some() 和 startsWith() javascript

[英]Combining some() and startsWith() javascript

I have an array with strings: const fruits = ['Apple', 'Banana', 'Orange']我有一个带字符串的数组: const fruits = ['Apple', 'Banana', 'Orange']

I am trying to write a function that returns true or false depending on if a string starts with any string in the array, which would be true for example 'Applepie' or 'Bananabread' .我正在尝试编写一个返回 true 或 false 的函数,具体取决于字符串是否以数组中的任何字符串开头,例如'Applepie''Bananabread'

I found startsWith() and some() , and combining them is sort of what I am after.我找到了startsWith()some() ,并将它们组合起来就是我所追求的。

How would I do this?我该怎么做?

You'd call some on the array and return the result of theString.startsWith(theArrayEntryForEachLoopIteration) , like this:您将在数组上调用some并返回theString.startsWith(theArrayEntryForEachLoopIteration)的结果,如下所示:

const theString = "Applepie";
const result = fruits.some(fruit => theString.startsWith(fruit));

result will be true if there was a match (your callback returned a truthy value), false if there wasn't (your callback never returned a truthy value).如果匹配(您的回调返回一个真值),则result将为true否则为false (您的回调从未返回一个真值)。 some will also stop looking the first time your callback returns a truthy value, since there's no point in looking further. some还会在您的回调第一次返回真值时停止查找,因为没有必要进一步查找。

Live Example:现场示例:

 const fruits = ['Apple', 'Banana', 'Orange']; // Example where it's there: const theString = "Applepie"; const result = fruits.some(fruit => theString.startsWith(fruit)); console.log(result); // Example where it isn't const theString2 = "Toffeepie"; const result2 = fruits.some(fruit => theString2.startsWith(fruit)); console.log(result2);

MDN has good reference and tutorial content: some , startsWith . MDN 有很好的参考和教程内容: somestartsWith

 const text = 'Applepie'; //Input Text const fruits = ['Apple', 'Banana', 'Orange']; console.log(fruits.some(v => text.startsWith(v)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM