+ 5

Can someone explain this to me plz? Thanks in advance.

var str = 'I love JavaScript!', j = 0, res = []; while(( j = str.indexOf('',j+1))>0){ res.push( j+1);} how many elements will be pushed into res?

23rd Jan 2018, 3:09 PM
Mazin Ayash
Mazin Ayash - avatar
2 Antworten
+ 5
You will have a error. A infinite loop will occur as ( j = str.indexOf('',j+1)) will always be greater than 0. If you have something like this: var str = 'I love JavaScript!', j = 0, res = []; while(( j = str.indexOf('',j+1))<str.length){ res.push(j+1); } you would get 17 pushes, but the array will start at 2 and go to 18, as there are two j+1 in the code. If you did the following code instead you would still get 17 pushes with its elements being 1 through 17 instead: while(( j = str.indexOf('',j+1))<str.length){ res.push(j); } Look here for more details: https://code.sololearn.com/WfBVYERG3FDh
23rd Jan 2018, 5:50 PM
Annabella Atherton Rosen
Annabella Atherton Rosen - avatar
+ 4
@Bryan Daniel Rosen thank you so much that was satisfying.
24th Jan 2018, 12:29 PM
Mazin Ayash
Mazin Ayash - avatar