javascript – 比较字符串和字符串数组的最快方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 比较字符串和字符串数组的最快方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2460字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 比较字符串和字符串数组的最快方法](/upload/InfoBanner/zyjiaocheng/805/ac2a283cdcc34421925643925d2502e3.jpg)
我有一个数组,让我们说:
var myArray = ["ibira", "garmin", "hide", "park", "parque", "corrida", "trote", "personal", "sports", "esportes", "health", "saúde", "academia"];
var myString = "I went to the park with my garmin watch";
检查我的String是否包含myArray中的任何单词的快速方法是什么?
贝娄是我的代码,但我不确定它是不是最好的方式…
function score(arKeywords, frase) {
if (frase == undefined) {
return 0;
} else {
var indice = 0;
var indArray = arKeywords.length;
var sentencaMin = frase.toLowerCase();
for (i = 0; i < indArray; i++) {
if (sentencaMin.search(arKeywords[i]) > 0) { indice++; }
}
return indice;
}
}
请帮助我.该函数将以很多字符串运行!
谢谢你们 :)
解决方法:
根据这句话,从问题:
What is [a] way to check if my String has any of the words in
myArray
?
(强调我的.)
我建议以下内容,它将测试提供的字符串中提供的字符串中是否存在“some”字样.这 – 理论上 – 一旦匹配数组中存在的字符串中的任何单词,就会停止比较:
var myArray = ["ibira", "garmin", "hide", "park", "parque", "corrida", "trote", "personal", "sports", "esportes", "health", "saúde", "academia"],
myString = "I went to the park with my garmin watch";
function anyInArray(needles, haystack) {
// we split the supplied string ("needles") into words by splitting
// the string at the occurrence of a word-boundary ('\b') followed
// one or more ('+') occurrences of white-space ('\s') followed by
// another word-boundary:
return needles.split(/\b\s+\b/)
// we then use Array.prototype.some() to work on the array of
// words, to assess whether any/some of the words ('needle')
// - using an Arrow function - are present in the supplied
// array ('haystack'), in which case Array.prototype.indexOf()
// would return the index of the found-word, or -1 if that word
// is not found:
.some(needle => haystack.indexOf(needle) > -1);
// at which point we return the Boolean, true if some of the
// words were found, false if none of the words were found.
}
console.log(anyInArray(myString, myArray));
var myArray = ["ibira", "garmin", "hide", "park", "parque", "corrida", "trote", "personal", "sports", "esportes", "health", "saúde", "academia"],
myString = "I went to the park with my garmin watch";
function anyInArray(needles, haystack) {
return needles.split(/\b\s+\b/).some(needle => haystack.indexOf(needle) > -1);
}
console.log(anyInArray(myString, myArray));
参考文献:
> Array.prototype.indexOf().
> Array.prototype.some().
> Arrow functions.
> Guide to JavaScript Regular Expressions (MDN).
> String.prototype.split().
内容总结
以上是互联网集市为您收集整理的javascript – 比较字符串和字符串数组的最快方法全部内容,希望文章能够帮你解决javascript – 比较字符串和字符串数组的最快方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。