N
N
Nikolay372019-01-29 15:34:18
Node.js
Nikolay37, 2019-01-29 15:34:18

How is the condition incorrectly fulfilled?

go()

function go(){
if (i < body["car"].length){
 if(body["car"][i].hasOwnProperty('class') == false){
 i++ 
 go()
 }
 console.log('ok')
 i++
 go()
} else if (i>= body["car"].length){
  console.log('exit')
}
}

Why does everything run well until the condition if(body["car"][i].hasOwnProperty('class') is not met?
For example, a function is executed, and then the condition with checking the element is fulfilled, everything is fine, then the go function is called again and if suddenly the element is I=14, and body["car"].length = 15, then we increase i++ (i.e. i=15), after calling the go function and this condition if (i < body["car"].length) is TRUE, why? How can it be true? After all, i == body['car'].length, and no less than him

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Skibin, 2019-01-29
@Nikolay37

Checking a slightly supplemented

body = {"car": [
  'asd',
  'ddddd',
  {
    class: 'asd'
  },
  'dddd'
]}

i = 0

function go(level = 1) {
  console.log(i, level)
  if (i < body["car"].length) {
    if (body["car"][i].hasOwnProperty('class') == false) {
      i++
      go(level + 1)
    }
    console.log('ok')
    i++
    go(level + 1)
  }
  else if (i >= body["car"].length) {
    console.log('exit')
  }
}

We have a conclusion:
0 1
1 2
2 3
ok
3 4
4 5
exit
ok
5 5
exit
ok
6 3
exit
ok
7 2
exit

Accordingly, we look at what level of nesting, i.e. everything works correctly, because we still need to exit the recursion
. But if we add return
function go(level = 1) {
  console.log(i, level)
  if (i < body["car"].length) {
    if (body["car"][i].hasOwnProperty('class') == false) {
      i++
      return go(level + 1)
    }
    console.log('ok')
    i++
    return go(level + 1)
  }
  else if (i >= body["car"].length) {
    console.log('exit')
  }
}

That conclusion will also change.
0 1
1 2
2 3
ok
3 4
4 5
exit

Perhaps it was required?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question