检查IF/OR中的多个条件,并且是EMPTY Javascript

Checking multiple conditions in an IF/OR and is EMPTY Javascript

本文关键字:Javascript EMPTY 条件 IF OR 检查      更新时间:2023-09-26

我有一个if语句,我想检查它是否是其中一个字符串,是否为空,但我不知道如何正确拼写。这是基本的,但是,我不知道如何在谷歌上使用这个词。非常感谢!

if(condition1 == "string" || condition2 == "string" && is empty){
    do this
}

编辑:参考您的jsFiddle 更新

//object drill down
var colField = evt.cell.field; //this gives me the column names of the grid in dojo
var mystring = item[colField] || ""; // gets item based on colField property
var fields = ["Owner", "Home", "Realtor", "Broker"]; // fields to check colField against
//here is the conditional statement. if column Owner, Home, Realtor or Broker property is empty in that object do the following
if(fields.indexOf(colField) !== -1 && mystring === "") {
}

更新的jsFiddle:http://jsfiddle.net/3AXN7/4/

由于您要检查的列不止两列,因此将所有列名放在一个数组中,然后检查colField是否在数组中,而不是将所有这些条件放在if语句中,会更加清晰和可维护。

唯一的问题是IE6-8不支持indexOf。如果你想确保这适用于所有浏览器,你需要提供indexOf的默认实现。您可以使用以下代码完成此操作:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
    "use strict";
    if (this === void 0 || this === null)
      throw new TypeError();
    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;
    var n = 0;
    if (arguments.length > 0) {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }
    if (n >= len)
      return -1;
    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);
    for (; k < len; k++) {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
if((typeof condition1 == 'string' && condition1.length == 0) || (typeof condition2 == 'string' && condition2.length == 0))

对此进行细分,(typeof condition1 == 'string' && condition1.length == 0)只需检查变量是否为字符串并且长度为0。如果它的计算结果为false,它将检查condition2是否是字符串并且长度为0。如果任一语句为true,则If语句将返回true。