在函数中设置默认变量值 [英] Setting a default variable value in a function
问题描述
我正在做很多前端开发,我发现自己做了很多这样的事情:
I am doing a lot of front-end developement and I see myself doing this a lot :
function doSomething(arg){
var int = arg ? arg : 400
//some code after
}
所以我想知道如果这是一种方法,但更短更清洁(我不喜欢在同一行中看到 arg
两次)。
So I was wondering if the was a way to do this, but shorter and cleaner (I don't like to see arg
twice in the same line).
我见过有些人这样做:
var int = arg || 400;
由于我不知道我需要放置价值,我试过 arg || 400
和 400 || arg
,但它总是将 int
设置为右边的值,即使 arg
未定义。
And since I don't know in wich order I needed to place the value, I tried arg || 400
and 400 || arg
, but it will always set int
to the value at the right, even if arg
is undefined.
我知道在PHP中你可以做类似函数doSomething(arg = 400)
来设置一个默认值,在jQuery插件中你可以使用 .extend()
来获得默认属性,但是单个变量有一个简短的方法吗?或者我必须继续使用我的方式?
I know in PHP you can do something like function doSomething(arg = 400)
to set a default value and in a jQuery plugin you can use .extend()
to have default property, but is there a short way with a single variable? Or do i have to keep using my way?
感谢您的帮助,如果您能给我资源,我们将不胜感激。
Thank for any help and if you can give me ressources, it would be appreciated.
推荐答案
确实没有比
var int = arg || 400;
事实上,如果你想允许arg作为<传递,那么正确的方法会更长code> 0 , false
或:
In fact, the correct way would be longer, if you want to allow arg to be passed as 0
, false
or ""
:
var int = arg===undefined ? 400 : arg;
轻微而频繁的改进是不申报新变量但使用原始变量:
A slight and frequent improvement is to not declare a new variable but use the original one:
if (arg===undefined) arg=400;
这篇关于在函数中设置默认变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!