0

I am just wondering what is the use of formIndex ofstring.indexOf(searchValue[, fromIndex])? I found a code like this:

 for (var sA in secondOnArray) { 
  if (firstOnArray.indexOf(secondOnArray[sA]) > -1) { // what is the purpose of [sA] there?
   result+= 0; 
  }
 }

Mozilla String indexOf() and w3Schools indexOf() examples seems very different?

  • 1
    "*what is the purpose of [sA] there*" [`for..in` loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) iterate through key/property names, in this case assigned to `sA`. The value still needs to be accessed. – Jonathan Lonowski Apr 26 '16 at 20:43
  • Related: [How to read API documentation for newbs?](http://stackoverflow.com/questions/10925478/how-to-read-api-documentation-for-newbs) – Jonathan Lonowski Apr 26 '16 at 20:52

1 Answers1

2

You are misunderstanding the notation.

ofstring.indexOf(searchValue[, fromIndex])

This means that the second argument to this function, fromIndex, is optional. If provided, it tells indexOf where to start looking. Otherwise, it is defaulted to 0.

To call the two-argument form, the syntax is:

ofstring.indexOf(value, index)

and note in particular that there are no square brackets. The square brackets are just a notational convenience for the documentation.

As for why the square brackets are there in your code, note that sA in the below code is an index. So to obtain the value of secondOnArray at index sA, we need to index it, hence the square brackets. This is unrelated to the two-argument form of indexOf.

for (var sA in secondOnArray) { 
  if (firstOnArray.indexOf(secondOnArray[sA]) > -1) {
    result += 0; 
  }
}

One might consider writing instead

secondOnArray.forEach(function (ele) {
  if (firstOnArray.indexOf(ele) > -1) {
    result += 0;
  }
});

which specifies the intention clearer.

Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
  • I really admire your answer, I am just wondering how did you master javascript? javascript is very hard to understand I am on free code camp now, any advise? – Glendon Philipp Baculio Apr 27 '16 at 17:53
  • @GlendonPhilippBaculio As with most languages, practice makes perfect. Aside from that, I recommend the [MDN Tutorials](https://developer.mozilla.org/en-US/docs/Web/JavaScript) if you have not seen those already. – Fengyang Wang Apr 27 '16 at 17:56
  • thank you for your recommendation. I am on free code camp now and I must say it's a very hard start, I will be going to check that, – Glendon Philipp Baculio Apr 27 '16 at 18:03