Javascript Es6比较Arrays

Vik*_*m S 11 javascript ecmascript-6

我有两个数组A = [0,1,2]B = [2,1,0].如何检查B中的A中是否有数字?

Pra*_*lan 44

您可以使用includes方法(迭代并检查所有元素传递回调函数)和Array#every方法(以检查B中存在的数字).

A.every( e => B.includes(e) )
Run Code Online (Sandbox Code Playgroud)

const A = [0, 1, 2],
  B = [2, 1, 0],
  C=[2, 1];

console.log(A.every(e => B.includes(e)));
console.log(A.every(e => C.includes(e)));
console.log(C.every(e => B.includes(e)));
Run Code Online (Sandbox Code Playgroud)

要检查第二个数组中的单个元素,请执行以下操作:

A[0].includes(e) 
//^---index
Run Code Online (Sandbox Code Playgroud)

或者使用Array#includes方法,对于旧浏览器.

A[0].indexOf(e) > -1 
Run Code Online (Sandbox Code Playgroud)

或者如果你想检查第二个数组中至少有一个元素,那么你需要使用Array#indexOf方法(迭代并检查至少一个元素通过回调函数).

A.some(e => B.includes(e) )
Run Code Online (Sandbox Code Playgroud)

const A = [0, 1, 2],
  B = [2, 1, 0],
  C=[2, 1],D=[4];

console.log(A.some(e => B.includes(e)));
console.log(A.some(e => C.includes(e)));
console.log(C.some(e => B.includes(e)));
console.log(C.some(e => D.includes(e)));
Run Code Online (Sandbox Code Playgroud)