简体   繁体   English

如何检查两个数组中的两个元素是否具有相同的索引?

[英]How to check if two elements inside two array have the same index?

I am new to javascript and want to know if there is a possible method to find out if an element inside an array has the same index as another element inside another array.我是 javascript 的新手,想知道是否有可能的方法来查明数组中的元素是否与另一个数组中的另一个元素具有相同的索引。

For example:例如:

var a = [4,6,3]
var b = [6,6,0]

how can I find out if the elements at index 1 in both arrays are the same in Javascript or using jQuery?如何确定 arrays 中索引 1 处的元素在 Javascript 中是否相同或使用 jQuery?

I cannot figure this and and any help would be deeply appreciated.我无法理解这一点,我们将不胜感激任何帮助。

Before learning those easy-to-use methods, I'm personally think you should learn to solve it in a very basic way first在学习那些简单易用的方法之前,我个人认为你应该先学会一个非常基本的方法来解决它

let index = -1; // -1 normally defined as not found

for (let i = 0 ; i < a.length ; i++) {
 for (let j = 0 ; j < b.length ; j++) {
  if (a[i] === b[j]) {
   index = i; // or index = j; is the same
  } // we won't need else since we don't need to do anything when the numbers are not match
 } 
}

Since you asked for the "magical" JS way,既然你要求“神奇”的 JS 方式,

a.some((i,j) => i == b[j]) should do what you're asking. a.some((i,j) => i == b[j])应该按照你的要求去做。

The some command runs a function across every element of the array and checks if any of them are true. some命令对数组的每个元素运行 function 并检查它们是否为真。 The function parameters i is the value of the elements in the first array and j is the index. function 参数i是第一个数组中元素的值, j是索引。 We use the j to get the value of b at that point and check if it's equal.我们使用j获取b在该点的值并检查它是否相等。

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

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