在JavaScript数组的比较 [英] comparison of array in javascript

查看:142
本文介绍了在JavaScript数组的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组说 A = [1,2,3] B = [1,2,3]

如果我这样做(A == B)返回false。如何在两个阵列,相同的值进行比较?

if i do (a==b) it returns false. how to compare two arrays with same values?

A [0] == B [0] 将返回true,但如何比较两个数组,而不是两个不同的阵列内2相同的元素?

a[0]==b[0] will return true, but how can we compare two arrays instead of 2 same elements inside two different arrays?

推荐答案

如果你想比较2个数组,你可以使用 JSON.stringify

If you want to compare 2 arrays, you could use JSON.stringify

JSON.stringify([1,2,3]) === JSON.stringify([1,2,3]); //=> true

这也将比较[嵌套]数组或对象之内[嵌套]数组内的数组:

It will also compare [nested] Objects within the array, or [nested] Arrays within an Array:

JSON.stringify([1,2,3,{a:1,b:2}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2}]); //=> true

JSON.stringify([1,2,3,{a:1,b:2,c:{a:1,b:2}}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2,c:{a:1,b:2}}]); //=> true

JSON.stringify([1,2,3,{a:1,b:2,c:[4,5,6,[7,8,9]]}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2,c:[4,5,6,[7,8,9]]}]); //=> true

本的jsfiddle 的,我打了一下的想法。

In this jsfiddle, I've played a bit with the idea

这篇关于在JavaScript数组的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆