简体   繁体   English

String.search()与String.split()以及JavaScript中的迭代

[英]String.search() vs String.split() and iteration in JavaScript

Lets say I have a string of fruit names 可以说我有一串水果名称

var string = "cherries,oranges,limes"

and an array of red fruit 和一系列红色水果

var array = ["tomatoes", "cherries", "raspberries"]

in javascript if I want to find if the string has any red fruit, I can do 在JavaScript中,如果我想查找字符串是否有任何红色水果,我可以

for(var i=0; i<array.length; i+=1){
    if(string.search(array[i])!=-1){
        return string.search(array[i]);

}

How would this compare with the following? 与以下内容相比如何?

var string_array= string.split(','); 
for(var i=0; i<array.length; i+=1){
    for(var j=0; j<string_array.length; j+=1){
       if(string_array[j]==array[i]){
       return string_array[j];
       }
}
}
return -1;

This can't work ; 这不行;

for(var i=0; i<array.length; i+=1){
   return string.search(array[i]);
}

You're returning at your first iteration. 您将在第一次迭代中返回。

So, this wouldn't compare very well. 因此,这不是很好。

BTW, if you're interested in script performance comparisons, I suggest you to try using jsperf . 顺便说一句,如果您对脚本性能比较感兴趣,建议您尝试使用jsperf

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

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