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.

1

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

I'm not completely sure, but I think that's equivalent to testing newValue[index] != null)
undefined === 'undefined' //false
typeof undefined === 'undefined'
Sorry but this doesn't check the things I need that I mentioned in my question.
:D sorry, i didnt notice that!
|
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;
}

Comments

0
if (newValue != null || newValue != undefined) && (oldValue != null || oldValue != undefined)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.