【问题标题】:Javascript test for null array not working空数组的Javascript测试不起作用
【发布时间】:2021-07-29 17:50:03
【问题描述】:

我正在使用具有 Javascript ES5 的工具。我正在尝试通过 if 条件测试数组是否为空。 if 之前的数组输出状态为“null”(参见下面的测试结果);但是,当对“null”进行 if 条件检查时,它认为应该在不应该继续处理时继续处理。我已经通过 if 语句以各种方式检查了一个空数组,当我转储调试数据并在数组上指定 [_OFNBRindex](当前已注释掉)时,它仍然通过了测试并由于空数组值而中止。"

前两个语句用于测试代码。 1)。一个空字符串,(给出问题的字符串),2),一个编号列表。编号列表将起作用。此外,指定“[_OFNBRindex]”的注释掉语句也会出错。

IF 的条件将停止空数组以便它们使用“else”语句,我缺少什么?

var _OFNBR = ""; // test value #1
// var _OFNBR = "100\n2\n\n40";  // test value #2

var _OFNBRindex = 0;

_OFNBR = _OFNBR.replace(/^[ \r\n\v\t\f\uFEFF\xA0]+|[ \r\n\v\t\f\uFEFF\xA0]+$/gi, "");
var _OFNBRLst = _OFNBR.match(/[0-9]+/g);

var _debug_text_msg = "Info: The DATA DUMP ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
java.lang.System.out.println(_debug_text_msg);

if ((_OFNBRLst !== undefined) || (_OFNBRLst !== "null") || (_OFNBRLst !== "") || (_OFNBRLst !== null)) {

  var _debug_text_msg = "Info: The NOT NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
  //var _debug_text_msg = "Info: The NOT NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst[_OFNbrindex] + "\"";
  java.lang.System.out.println(_debug_text_msg);

} else { // OFNBRLst is null, set to null

  var _debug_text_msg = "Info: The IS NULL ref code: " + "idx " + "\"" + _OFNBRindex + "\"" + "\"" + _OFNBRLst + "\"";
  java.lang.System.out.println(_debug_text_msg);

} // end if for OFNBRLst being null

_OFNBRindex++; // increment the _OFNBR index list.


// results

// First statement test #1

// Info: The DATA DUMP ref code: idx "0""null"
// Info: The NOT NULL ref code: idx "0""null"

// Second statement test #1
// Info: The DATA DUMP ref code: idx "0""100,2,40"
// Info: The NOT NULL ref code: idx "0""100,2,40"

【问题讨论】:

    标签: javascript ecmascript-5


    【解决方案1】:

    看起来您只有一些 OR,您需要 AND(如果您需要其他 !== 检查)。但是,您使用的String.protoype.match 的返回值是一个数组(如果找到匹配项)或null。所以你不需要任何!== 字符串检查。

    所以改变这一行:

    if ((_OFNBRLst !== undefined) || (_OFNBRLst !== "null") || (_OFNBRLst !== "") || (_OFNBRLst !== null)) {
    

    到这里:

    if (_OFNBRLst !== null) {
    

    【讨论】:

    • 你是对的!我错过了,谢谢。我编辑了我原来的答案。
    • 这行得通。我已经添加了在编写我的代码时遇到的所有可能的问题,这将进入。因此,为了让条件对我得到的所有其他错误执行它应该做的事情,OR's |或 ||应该是 & 或 &&。因此,为了检查空数组,使用了简化的建议。只是那些日子之一.....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多