admin管理员组文章数量:1336643
I often find myself using inline initialization (see example below), especially in a switch statement when I don't know which case loop will hit. I find it easier to read than if statements.
But is this good practice or will it incur side-effects or a performance hit?
for (var i in array) {
var o = o ? o : {}; // init object if it doesn't exist
o[array[i]] = 1; // add key-values
}
Is there a good website to go to get coding style tips?
I often find myself using inline initialization (see example below), especially in a switch statement when I don't know which case loop will hit. I find it easier to read than if statements.
But is this good practice or will it incur side-effects or a performance hit?
for (var i in array) {
var o = o ? o : {}; // init object if it doesn't exist
o[array[i]] = 1; // add key-values
}
Is there a good website to go to get coding style tips?
Share Improve this question edited Apr 4, 2010 at 16:57 Jon Seigel 12.4k8 gold badges60 silver badges93 bronze badges asked Feb 3, 2010 at 6:07 michaelmichael 4,5478 gold badges50 silver badges75 bronze badges2 Answers
Reset to default 7Another monly used pattern to do the same, is the use of the Logical OR ||
operator (a little bit more readable than your ternary IMHO):
//...
var obj = o || {};
This operator will return its second operand if the first one evaluates to false
, otherwise it will return the first one.
Is safe to use it when you expect an object, since those falsy values are null
, undefined
, NaN
, 0
, a zero-length string, and of course false
.
I find it useful to set default values on function arguments, when of course any of the falsy values are expected as valid by the function:
function test (arg1) {
arg1 = arg1 || "default value";
//..
}
Why not just declare it outside the loop?
var o = {};
for (var i in array) {
o[array[i]] = 1;
}
Otherwise no, I don't see a problem with what you're doing.
本文标签: javascriptcodestyle Is inline initialization of JS objects okStack Overflow
版权声明:本文标题:javascript - code-style: Is inline initialization of JS objects ok? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742416829a2470876.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论