我有以下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)
}
}
其中entity
和depot
是数组,但如果它们不保存数据,则它们=“NULL”
。
基本上,出于本解释的目的,我希望将 "NULL"
的长度读取为 0,或 if
entity
是一个长度为 1+ 的数组,depot
是一个字符串 - 满足 entity.length > depot.length
条件。
最佳答案
如果entity
和depot
都可以是“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)
}
仅当至少 entity
或 depot
不是 "NULL"
字符串且有效的非空数组时,此循环才会运行。
关于javascript - if else 比较数组和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34087480/