简体   繁体   English

JavaScript如何比较两个数组之间的值?

[英]JavaScript How to compare values between two arrays?

I am trying to learn how to compare two values between arrays with corresponding index. 我试图学习如何比较具有相应索引的数组之间的两个值。 Like 喜欢

var A = [2,12,3,42];
var B = [12,42,44,12];

So i know i need to loop in these arrays, but how do i compare two values based on index? 所以我知道我需要在这些数组中循环,但我如何根据索引比较两个值?

Like, index of [0] from A to compare with index of [0] from B, etc? 比如,从A的[0]索引与B的[0]索引比较等?

You will have to loop over arrays and compare every element. 您将不得不循环遍历数组并比较每个元素。

Considering, there can be arrays of different length, you should take max of them and check. 考虑到,可以有不同长度的数组,你应该采取最大的和检查。 Under such circumstances, if length of A is 4 and you try to access A[4] this will return undefined . 在这种情况下,如果A的长度为4并且您尝试访问A[4]则将返回undefined

 var A = [2, 12, 3, 42]; var B = [12, 42, 44, 12, 123]; var len = Math.max(A.length, B.length); console.log(len) for (var i = 0; i < len; i++) { console.log(A[i], B[i], A[i] === B[i]) } 

var firstElementEqual = A[0] === B[0]

This should be everything you need to do. 这应该是您需要做的一切。 You can simply reference the values by using the index and then comparing it like it's a normal variable. 您可以通过使用索引简单地引用值,然后将其比较为正常变量。

Example: 例:

var A = [2,12,3,42];
var B = [12,42,44,12];

console.log(A[0] === B[0]); // This will return false, as 2 A[0] is not equal to 12 B[0]

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

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