使用三元运算符检查 null
在下面的代码中,我传递一个 HMTL 元素并使用三元运算符检查传递的参数是否为 null。如果它不为 null,我将更改传递元素的 className。
var changeColorTo = {
grey: function(e){
e ? (e.className = "grey") : "" ;
},
red: function(e){
e ? (e.className = "red") : "" ;
},
green: function(e){
e ? (e.className = "green") : "" ;
},
blue: function(e){
e ? (e.className = "blue") : "" ;
}
};
上面的代码工作正常,除非我传递任何随机字符串,例如
changeColorTo.grey("random");
It 不会造成任何伤害。但我想知道上面的代码正确吗?我错过了什么吗?或者有没有更好的方法来达到相同的结果?
谢谢。
In below code, I pass an HMTL element and check whether parameter passed is null or not using ternary operator. If it is not null, I change the className of the passed element.
var changeColorTo = {
grey: function(e){
e ? (e.className = "grey") : "" ;
},
red: function(e){
e ? (e.className = "red") : "" ;
},
green: function(e){
e ? (e.className = "green") : "" ;
},
blue: function(e){
e ? (e.className = "blue") : "" ;
}
};
The above code works fine except when I pass any random string like
changeColorTo.grey("random");
It doesn't cause any harm. But I am wondering is above code correct? Do I miss anything? or is there any better way to achieve the same result?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将条件从
e
扩展到(e && e.className)
。这应该可以防止由于传入随机垃圾甚至非元素节点而导致脚本错误。更好的是,将该条件实现为
function hasClassName(e) { return ... }
并使用hasClassName(e)
作为测试。编辑:替换了不太完全兼容的
(typeof e=="object") && ('className' in e)
条件,根据评论。另请参阅如何我检查一个对象是否有 JavaScript 中的属性?You could expand your condition from just
e
to(e && e.className)
. That should prevent script errors resulting from passing in random junk or even non-element nodes.Better, implement that condition as
function hasClassName(e) { return ... }
and usehasClassName(e)
as your test.EDIT: Replaced less-than-fully-compatible
(typeof e=="object") && ('className' in e)
condition, per comments. See also How do I check if an object has a property in JavaScript?如果您传入一个字符串,代码就可以工作。但是,如果您想确保只传入 DOM 元素(最好严格一点),您可以将代码修改为:
有关
isNode
和的详细信息>isElement
工作,看看 这个stackoverflow回答。此代码还将确保您不会尝试更改null
或undefined
变量的className
属性,因为每个条件中的第一个条件这些函数(o instanceof Node
和o instanceof HTMLElement
)将失败,这确保isNode
和isElement
将返回false 表示null
和未定义
值。The code as it stands, will work if you pass in a string. However, if you want to be sure that you're only passing in a DOM element (it's better to be strict), you can modify your code to this:
For more information on how
isNode
andisElement
work, take a look at this stackoverflow answer. This code will also ensure that you won't try to change theclassName
attribute of anull
orundefined
variable since the first condition in each of those functions (o instanceof Node
ando instanceof HTMLElement
) will fail, which ensures thatisNode
andisElement
will return false fornull
andundefined
values.