如果以三元形式阻止,如何编写此内容
How to write this if else block in ternary form
我怎么能把它写成三元形式:
if (localStorage.getItem("txt")) {
newNote(localStorage.getItem("txt"), localStorage.getItem("name"));
} else {
newNote();
}
这似乎不起作用:
newNote(localStorage.getItem("txt") ? localStorage.getItem("txt"), localStorage.getItem("name") ? newNote();
要回答这个问题:
localStorage.getItem("txt")
? newNote(localStorage.getItem("txt"), localStorage.getItem("name"))
: newNote();
但老实说,我不明白为什么要以这种方式完成它,它的可读性较差。我只是让newNote
函数以一种方式,如果给出的参数是null
的,它就像一个没有参数的newNote()
。在这种情况下,您只需调用:
newNote(localStorage.getItem("txt"), localStorage.getItem("name"))
主代码和newNote
函数中没有任何if
:
function newNote(text, name) {
if (text === null) {
// alias to `newNote()`
} else {
// do whatever with `text` and `name`
}
}
试试这个:
var note = localStorage.getItem("txt")?newNote(localStorage.getItem("txt"), localStorage.getItem("name")):newNote();
语法boolean?expr1:expr2;
但我建议使用这样的东西:
var note=getNode(localStorage.getItem("txt"),localStorage.getItem("name"));
...
function getNode(txt,name){
return txt.length>0?newNote(txt,name):newNode();
}
localStorage.getItem("txt") ? newNote(localStorage.getItem("txt"), localStorage.getItem("name")) : newNote();
你为什么要以如此丑陋的方式这样做?
只需检查您的newNote
体是否设置了参数
function newNote(a, b) {
a = a || 'default';
b = b || 'default';
}
var a= localStorage.getItem("txt")?newNote(localStorage.getItem("txt"),localStorage.getItem("name"):newNote();
你不需要条件运算符。试试这个:
var txt = localStorage.getItem("txt");
newNote(txt, txt && localStorage.getItem("name"));
如果txt
是undefined
,那么newNote
将在没有任何参数的情况下被调用,如果是:txt
和name
。
我喜欢
@ZER0建议的方式,但我会这样做。
为了便于阅读,我将localStorage.getItem("txt")
和localStorage.getItem("name")
分配给一个变量:
var a = localStorage.getItem("txt");
var b = localStorage.getItem("name");
test(a ? [a, b] : []);
function test(options){
if(options.length > 0){
alert("a");
}else{
alert("ab");
}
}
相关文章:
- 如何编写HTML输入的JS内联
- 三元对短路
- 如何编写一个具有公共标头的批处理
- 在Redux中,我应该在哪里编写复杂的异步流
- 用玉石编写书法和手写笔
- 为函数代码编写测试
- 如何提供在javascript中编写对对象的重复访问以设置元素样式的简写
- 用JavaScript编写数字猜测程序
- jQuery:用ToggleClass编写超级菜单
- JavaScript 中三元条件和逻辑和运算符的运算符优先级
- 文档.编写方法问题
- 在CodeIgniter视图中将Javascript或jQuery代码作为PHP文件编写可以吗
- 这个javascript代码是如何编写的
- 三元运算符检查多个字符串
- 在node.js中编写单元测试的最佳方式是什么
- 我该如何编写一个CouchDB视图,列出每个存储文档的大小
- 通过键盘编写SVG文本
- 如何正确地在页面外编写DFP广告单元
- “createImageData()”和“new ImageData(()”有何不同
- 如果以三元形式阻止,如何编写此内容