为何或如何这是否证明了JavaScript数组的平等? [英] Why or how does this prove JavaScript array equality?

查看:120
本文介绍了为何或如何这是否证明了JavaScript数组的平等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个答案有一个简单的函数,将返回包含原始值数组的数组平等。

In this answer there is a simple function that will return array equality for arrays that contain primitive values.

不过,我不知道为什么它的工作原理。下面是函数:

However, I'm not sure why it works. Here is the function:

function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); }

我在下半场最感兴趣;该位:

I'm mostly interested in the second half; this bit:

!(a<b || b<a)

为什么在&LT; &GT; 工作比较阵列但当 == 不?

Why does the < and > work when comparing the arrays but the == doesn't?

如何做的比超过方法中的JavaScript的工作更少,更大?

How do the less than and greater than methods work within JavaScript?

推荐答案

通过&LT; / &GT; ,阵列被转换为字符串第一,因此没有提供检查平等的可靠方法。

With </>, the arrays are converted to strings first, and as such do not provide a reliable method of checking equality.

== ,因为对象是通过引用检查不工作:

== does not work because objects are checked by reference:

[] == []; // false, two separate objects

var a = [];
a == a; // true, refer to the same object

&LT; / &GT; 招是有缺陷的:

The </> trick is flawed:

var a = [1, [2, 3]],
    b = [[1, 2], 3];

!(a<b || b<a); // true

该计算结果为真正,因为它们都转换成字符串1,2,3前它们会被检出(&LT; / &GT; 做的对象而不是直接的工作)。

This evaluates to true, because they are both converted to the string "1,2,3" before they are checked (</> do not "directly" work for objects).

所以基本上,你是比较字符串的平等。对于字符串, A == b 确实是一样的(A&LT; b || B&LT; A)! - &LT; / &GT; 字符串检查字符codeS,所以两个相等的字符串既不是小,也不大,因为这不是在字符串的任何字符code的情况。

So basically, you are comparing equality of the strings. For strings, a == b is indeed the same as !(a<b || b<a) - </> for strings check character codes, so two equal strings are neither "smaller" nor "greater" because that's not the case for any character code in the strings.

这篇关于为何或如何这是否证明了JavaScript数组的平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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