JavaScript 中的条件检查无效

Conditional check in JavaScript not working

我正在尝试下面的代码,但它没有按预期工作。我想检查单元格值是否有 India 或 UnitedStatedofAmerica 或 Germany 或 Switzerland 然后进去,如果它是 undefinednull 或空白,或者它不包含文本位置然后转到 else 并将值设置为 ROW,但它不起作用。

所以每次它给我结果 ROW 即使单元格有 India 或 UnitedStatedofAmerica 并且当它为 null 时它进入真实条件并抛出拆分错误,因为 cell.Value 为 null

3 示例 cell.Value

"Lorem Ipsum is simply dummy text of the printing and typesetting;Location India, Mumbai;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of 的印刷和排版Lorem Ipsum is simply dummy text of印刷排版

"Location 印度;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of printing and typesetting;Lorem Ipsum is simply dummy text of the printing和排版Lorem Ipsum 只是打印和排版的虚拟文本

"Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of printing and typeseted;Lorem Ipsum is simply dummy text of printing and typetingLorem Ipsum is;Location United Stated美国;只是打印和排版的虚拟文本

if (cell.Value.split('Location')[1].split(',')[0].replace(/\s/g, "") === "India" || cell.Value.split('Location')[1].split(',')[0].replace(/\s/g, "") === "Germany" || cell.Value.split('Location')[1].split(',')[0].replace(/\s/g, "") === "UnitedStatesofAmerica" || cell.Value.split('Location')[1].split(',')[0].replace(/\s/g, "") === "Switzerland" || cell.Value !== 'undefined' || cell.Value !== null || cell.Value !== "" || cell.Value.toLowerCase().indexOf("Location") !== -1) {
  persona.country = cell.Value.split('Location')[1].split(',')[0].replace(/\s/g, "");
} else {
  persona.country = "ROW"
}

您可以使用一些变量和一系列想要的国家来简化某些部分。

const
    value = cell.Value || '',
    country = value.split('Location')?.[1]?.split(',')[0].replace(/\s/g, ""),
    countries = ["India", "Germany", "UnitedStatesofAmerica", "Switzerland"];

persona.country = countries.includes(country)
    ? country
    : "ROW";

如果 cell.Valuenullundefined 那么调用 .split 将抛出错误。您可以在 toif 语句的开头添加对 cell.Value 的虚假检查。

if(cell.Value && cell.Value.split...