1

I'm developing window application for comparing source code with node-webkit and I want to check null function.

my code is

function click1() {
      if(swap == true)
        var lines1 = $('textarea1').val().split('\n'); //compare1
        var lines2 = $('textarea2').val().split('\n'); //compare2

        if (lines1.length == lines2.length) {
             for (var i=0;i<lines1.length;i++) {
                 if(lines1[i] == lines2[i]) {
                      var keys = lines1[i].match(/\b[\w\d]*/g);
                      if(keys[0] == null) { //**problem line**
                          alert('This line is null');
                      } else {
                          alert(keys[0]);
                      }
                 }
             }

If i execute this click event, error occured.

Uncaught TypeError : cannot read property '0' of null

How I can fix this problem..

help me

ps. I tried keys[0] === null, typeof keys[0] == 'null', !keys[0] etc...

4 Answers 4

1

just use this:

if(keys[0]) {
  alert(keys[0]);
} else {
  alert('This line is null');
}
Sign up to request clarification or add additional context in comments.

4 Comments

.match may return null, null[0] will throw that error. You have to guard against that case too.
i believe keys is not array. remove the "[0]".
Oh, Thanks Dr.Stitch!! i solved problem thanks to your solution. but if key is not null, keys[0] is worked
great! happy to help. :)
0

its not keys[0] that's null. its keys. Look at the error, it can't read property 0 of null meaning it can't read the 0 property of the null variable keys. Your regular expression isn't matching anything, so it returns null.

solution:

if (keys && keys[0])

2 Comments

Thanks to your adivce. I understand keys not array, but if keys is not null, keys[0] is exist. Why existed [0] ?
I think I understand your question. For the answer I shall point you to this link here. match will return an array if it finds a match and null if no matches are found. It's best to learn how the method works before you agonize over it.
0

array[index] is null or undefined.

if (keys[0] == 'undefined' || keys[0] == null) {
   alert('This line is null');
} else {
   alert(keys[0]);
}

array[index] is null and undefined.

if (keys[0] == 'undefined' && keys[0] == null) {
   alert('This line is null');
} else {
   alert(keys[0]);
}

1 Comment

Thanks to advice Jakir!
0

Try this:

if(!keys || keys.length === 0) { //**problem line**
  alert('This line is null');
}else {
  alert(keys[0]);
}

1 Comment

Thanks to your adivice saikumar!

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.