for()循环比较2个数组,然后更改另一个数组。仅限JavaScript

时间:2022-09-25 09:09:52

I hope someone can help me with this.

我希望有人可以帮助我。

I have 2 equal length arrays, and I want to compare them, string by string. if array[3] equals otherArray[3], I want to change the value of yet anotherArray[3]

我有2个相等长度的数组,我想比较它们,逐个字符串。如果array [3]等于otherArray [3],我想改变另一个Array [3]的值

I tried to do this with this code, but for some reason it doesnt change the 3th array, and my console doesnt give any errors.

我尝试使用此代码执行此操作,但由于某种原因它不会更改第3个数组,并且我的控制台不会给出任何错误。

Here is the code:

这是代码:

for (i = array.length; i > 0; i--) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    }
}

It should be pretty straight forward, but unfortunatly I cant get it to work. And please no JQuery or other plugins. Thank you.

它应该是非常直接的,但不幸的是我无法让它工作。请不要使用JQuery或其他插件。谢谢。

4 个解决方案

#1


Your Code is correct. Just a small change is required

您的准则是正确的。只需要进行一些小改动

for (i = array.length-1; i >= 0; i--) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    } else {
    targetArray[i] = "";
    }
}

You have to make null the array values which are not equal, otherwise it will give an undefined.

你必须使不相等的数组值为null,否则它将给出一个未定义的数组。

#2


for (var i = 0; i < array.length; i++) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    }
};

#3


Try this,

for (i = array.length - 1; i >= 0; i--) {
  for (j = otherArray.length - 1; j >= 0; j--) {
    if (array[i] === otherArray[j]) {
      targetArray[i] = "string";
    }
  }
}

#4


Is it safer to implement like this if you don't know array index

如果你不知道数组索引,那么实现这样更安全

for (var i in array) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    }
}

#1


Your Code is correct. Just a small change is required

您的准则是正确的。只需要进行一些小改动

for (i = array.length-1; i >= 0; i--) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    } else {
    targetArray[i] = "";
    }
}

You have to make null the array values which are not equal, otherwise it will give an undefined.

你必须使不相等的数组值为null,否则它将给出一个未定义的数组。

#2


for (var i = 0; i < array.length; i++) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    }
};

#3


Try this,

for (i = array.length - 1; i >= 0; i--) {
  for (j = otherArray.length - 1; j >= 0; j--) {
    if (array[i] === otherArray[j]) {
      targetArray[i] = "string";
    }
  }
}

#4


Is it safer to implement like this if you don't know array index

如果你不知道数组索引,那么实现这样更安全

for (var i in array) {
    if (array[i] === otherArray[i]) {
        targetArray[i] = "string";
    }
}