javascript - How is indexOf returning the position of this example, shouldn't the result be -1? -


i know indexof searches position of value in string / array returns position thought must exact match if there's spaces. reading , confused why it's returning true if match partial.

normally how indexof return , expected

var array = ["aa", "bb", "a", "cc", "d", "this time home.", "it's christmas"]; // let's result >= 0 return true else false console.log(array.indexof("aa") + " aa");   // 0 --true console.log(array.indexof("a") + " a");     // 2 --true console.log(array.indexof("c") + " c");     // -1 --false console.log(array.indexof("dd") + " dd");   // -1 --false console.log(array.indexof("the time") + " time");   // -1 --false console.log(array.indexof("it's christmas") + " christmas");    // 6 --true 

and saw in book , don't understand why it's returning true meaning it's found in array.

string.prototype.cliche = function(){     var cliche = ["lock , load", "touch base", "open kimono"];      (var = 0; < cliche.length; i++){         var index = this.indexof(cliche[i]);         if(index >= 0){             return true;         }     }     return false; }  var sentences = ["i'll send car around pick up.",                 "let's touch base in morning , see are",                 "we don't want open kimono, want inform them."];  for(var = 0; < sentences.length; i++){     var phrase = sentences[i];     if(phrase.cliche()){         console.log("cliche alert: " + phrase);     } } 

the cliche array in function has partial of phrase touch base , on

but in sentence array value let's touch base in morning , see are indexof returns true 1 if it's partial of phrase matches cliche value.

how work?

that's because different methods:

  • array.prototype.indexof returns first position value found (using strict equality algorithm) in array.
  • string.prototype.indexof returns first position string contained (is substring) in string.

example:

["aa"].indexof("a"); // -1 (not found) "aa".indexof("a");   // 0 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -