0

I have the following Javascript function where the parameters newValue and oldValue are arrays of integers and the same length. Any values in these arrays can be an integer, undefined or null:

function (newValue, oldValue) {


});

Is there some way that I could check the values in the arrays one element at a time and then do an action only if:

newValue[index] is >= 0 and < 999
oldValue[index] is >= 0 and < 999
newValue[index] is not equal to oldValue[index]

What I am not sure of is how can I handle in my checks and ignore the cases where newValue or oldValue are not null and not undefined? I know I can do a check as in if (newValue) but then this will show false when it's a 0.

Update:

I had a few quick answers so far but none are checking the right things which I listed above.

  • possible duplicate of [Detecting an undefined object property in JavaScript](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript) – Bergi Apr 09 '14 at 15:35

3 Answers3

1

compare against null and undefined:

if (newValue[index] !== null && typeof newValue[index] !== 'undefined') {}

for OPs update:

n = newValue[index];
o = oldValue[index];

if (
  n !== null && typeof n !== 'undefined' && n >= 0 && n < 999 &&
  o !== null && typeof o !== 'undefined' && o >= 0 && o < 999
) {
  // your code
}

for array-elements its not necessary to use typeof so n !== undefined is ok because the variable will exist.

n = newValue[index];
o = oldValue[index];

if (
  n !== null && n !== undefined && n >= 0 && n < 999 &&
  o !== null && o !== undefined && o >= 0 && o < 999 &&
  n !== o
) {
  // your code
}
phylax
  • 2,034
  • 14
  • 13
0

This will do it:

function isEqual (newValue, oldValue) {
    for (var i=0, l=newValue.length; i<l; i++) {
        if (newValue[i] == null || newValue[i] < 0 || newValue[i] >= 999
         || oldValue[i] == null || oldValue[i] < 0 || oldValue[i] >= 999)
            continue;
        if (newVale[i] !== oldValue[i])
            return false;
    }
    return true;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
if (newValue != null || newValue != undefined) && (oldValue != null || oldValue != undefined)
Easwar Raju
  • 253
  • 1
  • 4