-9

The following function is designed to take numbers out of a string and then add those numbers.

For example, you can enter a string like "What does the iphone6 cost in 2015?" and it should return 2021.

I was able to do 90% of the function, but don't know what the parseInt() function does in the code. I know it is necessary to make it work. Any explanation would be appreciated.

  function sumFromString(str){
  var sum=0;
  var numbers=str.match(/\d+/g);
  if(numbers==null){
    return 0
   }
  for(var i=0;i<numbers.length;i++){
  sum+=parseInt(numbers[i]);
   }
 return sum;
 }
kodave
  • 1
  • 3
  • 1
    In this case it just turns your `string` into a `number` – JohanP Mar 07 '17 at 02:21
  • 5
    Have you bothered to [check the documentation?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) I mean, good grief; google "javascript parseInt" and you'll get all the answers you need. – Pointy Mar 07 '17 at 02:21
  • https://www.w3schools.com/jsref/jsref_parseint.asp a string is being converted to Integer – Kasnady Mar 07 '17 at 02:21
  • 2
    I'm voting to close this question as off-topic because the answer can be found in [the fine manual](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt) – Phil Mar 07 '17 at 02:21
  • Your very first stop when you have a question should be Google. We're not your personal research assistants. It's fine to need some help, but please don't be helpless. At least make some sort of effort to figure things out yourself, and the most basic effort you can make is a simple Google search. – Ken White Mar 07 '17 at 02:23
  • Possible duplicate of [Why does parseInt(1/0, 19) return 18?](http://stackoverflow.com/questions/11340673/why-does-parseint1-0-19-return-18) – Smit Mar 07 '17 at 02:26

1 Answers1

1

At the moment numbers is an Array of Strings.

parseInt takes a string as its parameter, and tries to parse it into an integer.

In the code it is doing this so they can be added together.

If there was no parseInt, the result would be "62015" (as a string)

Worthy7
  • 1,455
  • 15
  • 28