如何在JavaScript中比较数组? [英] How do I compare arrays in JavaScript?

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

问题描述

有人可以描述这些表达的结果吗?

  [1,2,4]< [1,2,5] // true 
[1,3,4]< [1,2,5] // false


[1,2,3] === [1,2,3] // false
[1,2 ,3]< [1,2,3] // false
[1,2,3] == [1,2,3] // false
[1,2,3]> [1,2,3] // false


[1,2,3]< = [1,2,3] // true
[1,2 ,3]> = [1,2,3] // true

感谢您的帮助和快速回答!

解决方案

在JavaScript中,几乎所有东西都是对象。原始类型根据需要在原始版本和对象版本之间自动封装。



当您比较JavaScript中的对象时,实际上是在比较它们是否是相同的引用(例如指向相同的内存地址)。 此处的证据

  var a = [1,2,3]; 
b = a;
b.push(5);
console.log(a); // 1,2,3,5

在这种情况下 a == b a === b 将产生 true 。如果我想比较两个单独的数组,那么我需要循环遍历它们并逐个元素进行比较。



在下面的例子中,我可以使用一个技巧。 现场演示

  var x = [1,2,3]; 
var y = [1,2,4];
var z = [1,2,3];
var equals = x.join()。localeCompare(y.join())== 0; // x with y
var equals2 = x.join()。localeCompare(z.join())== 0; // x with z
document.body.innerHTML + = equals +< br />;
document.body.innerHTML + = equals2 +< br />;

在你奇怪的情况下

 数组([],null,undefined,null)==,,,; 

在JavaScript中, == 运算符将执行它可以执行的所有类型转换/转换以检查是否相等。它会尝试将 String String 进行比较,此时左侧是 Array 将使用简单的 toString()调用转换为 String ! / p>

此处 ,我猜答案现在显而易见了。


Can someone please describe the outcome of these expressions?

  [1, 2, 4] < [1, 2, 5]  // true
  [1, 3, 4] < [1, 2, 5]  // false


  [1, 2, 3] === [1, 2, 3]   // false
  [1, 2, 3] <   [1, 2, 3]   // false
  [1, 2, 3] ==  [1, 2, 3]   // false
  [1, 2, 3] >   [1, 2, 3]   // false


  [1, 2, 3] <= [1, 2, 3]   // true
  [1, 2, 3] >= [1, 2, 3]   // true

Thanks for help and fast answer !

解决方案

In JavaScript almost everything is an Object. There are primitive types which auto-box between primitive and Object version as needed.

When you compare Objects in JavaScript, you are actually comparing if they are the same reference(e.g point to the same memory address). Proof here

 var a = [1, 2, 3];
 b = a;
 b.push(5);
 console.log(a); // 1, 2, 3, 5

In this case a == b or a === b will yield true. If I want to compare two separate arrays, then I need to loop through them and compare element by element.

In the following case, I can use a trick though. Live demo

var x = [1, 2, 3];
var y = [1, 2, 4];
var z = [1, 2, 3];
var equals = x.join("").localeCompare(y.join("")) == 0; //x with y
var equals2 = x.join("").localeCompare(z.join("")) == 0; //x with z
document.body.innerHTML += equals + "<br />";
document.body.innerHTML += equals2 + "<br />";

In your weird case

Array([],null,undefined,null) == ",,,";

In JavaScript the == operator will perform all the type casts/conversions it can perform to check for equality. It will try to compare a String with String, at which point the left hand side, the Array will be converted to a String using a simple toString() call!

Look here, I guess the answer is now obvious.

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

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