0

Can someone explain me why if condition in this code isn't working?

        var zaposleni=[];
        for(i=1;i<brOpcija;i++){
        zaposleni.push(myOpts[i].value);
        }

        var zaposleniRestoran=[];
        for(i=1;i<brOpcija;i++){

            if(zaposleni[i].split(' ').slice(2).join(' ') == vrednostSelekta()){
                zaposleniRestoran.push(zaposleni[i].split(' ').slice(0,2));
            }
        }

Here,i have array zaposleni where i push some values,and array is look like ["name" "surname" "restaurantName"],and then i am checking if restaurantName == vrednostSelekta() (where vrednostSelekta() is return value of some function in javascript),but i always get this error:

Uncaught TypeError: Cannot read property 'split' of undefined
    at HTMLSelectElement.<anonymous> (zaposleni.js:51)
    at HTMLSelectElement.handle (jquery.min.js:55)
    at HTMLSelectElement.o (jquery.min.js:49)

But when i erase this if,and then type that in debugger,i get no error and it is working there..Thanks in advance!

1
  • As I know every array for lop should start with i=0; because every array first 'item' has index 0, if you have one 'item' in array 1<1 is not true so it will return false. By your language I should say "zagrej malo stolicu to su osnovne stvari". Commented Feb 11, 2017 at 23:52

2 Answers 2

1

Looks like the "zaposleni" array is empty or maybe there is only one element in it. Your for loop is starting at "i=1".

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

Comments

1

In the error, Cannot read property 'split' of undefined means that you're calling .split(...) to something that isn't defined.

This means that at the beginning of the if, the script is stopping when zaposleni[i] is not defined.

This is probably because i is bigger than the length of zaposleni at the biggest value for i, as you're iterating up to the same value, but you're starting to push at i=1 rather than i=0, as array indices in JS start at 0. In other words, you're adding a value at zaposleni[0], not zaposleni[last index value], and requiring from zaposleni[1] up to zaposleni[last index value], so the last one will be undefined.

The issue may also be that myOpts[i].value is probably undefined for some values of i, so I would recommend checking that

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.