我有一个if
语句:
if (argList["foo"] === "bar" || argList === "bar"){
// some code
}
我想知道是否有更短或更优雅的方式来编写此条件。
我为什么这样写这句话?我有一个名为startTool(argList(的函数,另一个叫做startCreate(argList(。
mod.zsh_apiStartTool = function(argList, callback) {
// some code
if (argList["tool"] === "measure" || argList === "measure"){
//some code to start the tool
}
if (argList["tool"] === "scanning"|| argList === "scanning"){
// some code to start the tool
}
ZSH_JS_API_ERROR(callback);
return;
}
mod.zsh_apiStartCreate = function(argList, callback) {
// some code
if (argList["tool"] === "measure"){
mod.zsh_apiStartTool("measure")
}
if (argList["tool"] === "scanning"){
mod.zsh_apiStartTool("scanning");
}
ZSH_JS_API_ERROR(callback);
return;
}
所以当我从startCreate遇到startTool时,我的var不是argList["foo"] === "bar",而是argList === "bar">
为了确保属性存在,恕我直言,最好使用帮助程序作为:
- 打字稿猫王案例
-
洛达什
_.get()
法if (_.get(argList, "foo") === "bar" || argList === "bar"){ // some code }
仅当您尝试访问更深层次(如 argList["foo"]["bar"(时,问题才很严重
JSON.stringify
另一种选择是字符串化对象并在此处查找值,如果您知道"bar"是对象中的确定性值(因此没有其他属性可以在argList中保存它(:
JSON.stringify(argListObj).includes("bar")
const argListObj = { foo: "bar" };
const argListString = "bar";
console.log(JSON.stringify(argListObj).includes("bar"));
console.log(JSON.stringify(argListString).includes("bar");
// Console logs true, true