0

yesterday I asked question which have been answered correctly. Now I want spend more time to understand that function which answered yesterday. In that function loop is adding value '7' in 'num' variable. I want to know how its adding value in 'num'.

var Arr = [ 'h78em', 'w145px', 'w13px' ]

function stringToNum(str){
  num = 0;
  for (i = 0; i < str.length; i++) 
    if (str[i] >= '0' && str[i] <= '9') 
      num = num * 10 + parseInt(str[i]);
  return num;
}

alert(stringToNum(Arr[0]));
​

here is fiddle

2
  • mdas rules apply you multiplied num by 10 first before adding the parse value, therefore 0 * 10 + 78 = 78 Commented Aug 31, 2012 at 6:15
  • if you remove *10 + parseInt(str[i]); and then alert num it will return 7, i want to know how it is 7 is passing to num variable Commented Aug 31, 2012 at 6:21

3 Answers 3

2

In the given code, when the function is called, the if condition checks for each string in the passed value and when the variable is a number, the following code is executed

   if (str[i] >= '0' && str[i] <= '9') 
      num = num * 10 + parseInt(str[i]);

so in the given string, the first number occurs is 7. Since the value of num is initially zero the value of num will be,

 num=( 0 *10) + 7

so num=7 in the first occurence of the number. On the second occurence of a number, ie 8

the value of num will be,

  num=(7*10)+8

hence the value is 78

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot sir ji. You have very nice way to explain.
1

The below function will be much simpler.

function stringToNum(str) {
  return +str.replace(/\D/g, '');
}

Update:

With your code:

init : num = 0
met 7: num = 0 * 10 + 7 -> num = 7
met 8: num = 7 * 10 + 8 -> num = 78

3 Comments

i dont want new answer for the same, i just want understand this
@amit What is the part you can't understand?
@amit It's much better to get rid of non-digits using regex than to iterate over the string parsing each digit individually (+1 @xdazz). It's cleaner, easier to understand at a glance, and should perform better (certainly as the string grows longer)
1

1 iteration: num = 0; // h

2 iteration: num = 0 * 10 + 7; // 7

3 iteration: num = 7 * 10 + 8; // 8

4 iteration: num = 78; // e

5 iteration: num = 78; // m

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.