javascript - if else 比较数组和字符串

标签 javascript if-statement

我有以下if-else:

if (entity.length > depot.length) {
    for (var i = 0 ; i < entity.length; i++) {
        promises.push(this.getDataFromREST(security, i));
        console.log(entity, depot)
    }
} else {
    for (var i = 0 ; i < depot.length; i++) {
        promises.push(this.getDataFromREST(security, i));
        console.log(entity, depot)
    }
}

其中entitydepot是数组,但如果它们不保存数据,则它们=“NULL”

基本上,出于本解释的目的,我希望将 "NULL" 的长度读取为 0,或 if entity是一个长度为 1+ 的数组,depot 是一个字符串 - 满足 entity.length > depot.length 条件。

最佳答案

如果entitydepot都可以是“NULL”字符串或有效数组,您只需检查“NULL”,计算一次长度并使用一个循环:

var loopLength = Math.max(entity === 'NULL' ? 0 : entity.length, 
                           depot === 'NULL' ? 0 : depot.length);

for (var i = 0 ; i < loopLength; i++) {
    promises.push(this.getDataFromREST(security, i));
    console.log(entity, depot)
}

仅当至少 entitydepot 不是 "NULL" 字符串且有效的非空数组时,此循环才会运行。

关于javascript - if else 比较数组和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34087480/

相关文章:

javascript - 接下来如何将react js中的普通表转换为使用react bootstrap表

javascript - 如何更改我的 Controller 以使其与我的 View 充分分离?

javascript - 使用 angularjs 过滤器显示包含特定 css 类的元素

c - if语句中的执行顺序

c++ - 错误 c2106 : '=' : left operand must be I-value

javascript - 使用 for 循环和多个 if else 语句重构函数

javascript - 使用 javascript 读取文件

javascript - 在从 API 接收值之前调用 React 状态

javascript - 根据变量的值范围,是否有比使用 if-else 语句更快/更有效的方法来调用不同的函数?

java - 不知道为什么这个带有字符串的 if 语句不起作用