最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript How to compare values between two arrays? - Stack Overflow

programmeradmin5浏览0评论

I am trying to learn how to pare 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 pare two values based on index?

Like, index of [0] from A to pare with index of [0] from B, etc?

I am trying to learn how to pare 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 pare two values based on index?

Like, index of [0] from A to pare with index of [0] from B, etc?

Share asked Oct 22, 2016 at 14:08 Bokchee 88Bokchee 88 2771 gold badge6 silver badges19 bronze badges 1
  • 2 Possible duplicate of How to pare arrays in JavaScript? – Rajesh Commented Oct 22, 2016 at 14:15
Add a ment  | 

2 Answers 2

Reset to default 3

You will have to loop over arrays and pare 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.

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 paring 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]
发布评论

评论列表(0)

  1. 暂无评论