简体   繁体   English

如何遍历两个数组比较Javascript中的值?

[英]How can I loop through two arrays comparing values in Javascript?

I have the following Javascript function where the parameters newValue and oldValue are arrays of integers and the same length. 我有以下Javascript函数,其中参数newValue和oldValue是整数数组,并且长度相同。 Any values in these arrays can be an integer, undefined or null: 这些数组中的任何值都可以是整数,未定义或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? 我不确定的是如何处理检查并忽略newValue或oldValue不为null且未定义的情况? I know I can do a check as in if (newValue) but then this will show false when it's a 0. 我知道我可以像(newValue)一样进行检查,但是当它为0时将显示false。

Update: 更新:

I had a few quick answers so far but none are checking the right things which I listed above. 到目前为止,我有几个快速解答,但没有一个可以检查上面列出的正确内容。

compare against null and undefined : nullundefined比较:

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

for OPs update: 对于OP更新:

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. 对于数组元素,不必使用typeof所以n !== undefined可以,因为变量将存在。

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
}

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;
}
if (newValue != null || newValue != undefined) && (oldValue != null || oldValue != undefined)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM