Javascript比较3个值 [英] Javascript compare 3 values
本文介绍了Javascript比较3个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个值,我想比较f,g和h。我有一些代码来检查它们是否彼此相等,并且它们都不为空。我在网上看过,但找不到任何似乎可以回答我查询的内容。目前我正在按以下方式检查代码......
I have 3 values that I want to compare f, g and h. I have some code to check that they all equal each other and that none of them are null. I've had a look online but could not find anything that seemed to answer my query. Currently I am checking the code in the following way...
if(g == h && g == f && f == h && g != null && f != null && h != null)
{
//do something
}
这是漫长的啰嗦,我可能会添加更多的值,所以我只是想知道是否有一种更快捷的方法可以检查没有值是否为空并且所有值都相等?
This is quite long winded and I might be adding more values, so I was just wondering if there is a quicker way to check that none of the values are null and that all the values equal each other?
提前感谢您的帮助。
推荐答案
您可以将其缩短为
if(g === h && g === f && g !== null)
{
//do something
}
用于比较多个值的实际方法(无论其数量)
(灵感来自/简化 @Rohan Prabhu 回答)
function areEqual(){
var len = arguments.length;
for (var i = 1; i< len; i++){
if (arguments[i] === null || arguments[i] !== arguments[i-1])
return false;
}
return true;
}
并用
if( areEqual(a,b,c,d,e,f,g,h) )
{
//do something
}
这篇关于Javascript比较3个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文