![](/img/trans.png)
[英]JavaScript combining && statements in a variable to be true or false
[英]Nested (Condition) ? true:false statements in JavaScript
在以下代碼段中,
var paintMode = data.hasOwnProperty('regions') ?
'regions' : data.hasOwnProperty('vpcs') ?
'vpcs' : data.hasOwnProperty('zones') ?
'zones' : data.hasOwnProperty('subnets') ?
'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null;
我使用了一個嵌套的(condition) ? true : false
(condition) ? true : false
這可以接受嗎? 優化了嗎? 如果不好,還有其他選擇嗎?
它在執行一些SVG操作的遞歸函數中使用,如果您好奇的話,這里是函數片段。
function paintGroups(data) {
var paintMode = data.hasOwnProperty('regions') ? 'regions' : data.hasOwnProperty('vpcs') ? 'vpcs' : data.hasOwnProperty('zones') ? 'zones' : data.hasOwnProperty('subnets') ? 'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null,
depth = data[paintMode].length,
i,
Shape; //= raphealObj.rect();
// Register stacking order
// Paint a shape with styles based on paintMode
// Store its id & Label for other ops.
if(paintMode) {
for(i = 0; i < depth; i++) {
paintGroups(data[paintMode][i]);
}
}
// to reverse the order of paint - place your statements here
}
一般來說,由於分支預測,緩存,yada yada yada,使用二進制操作應該比帶有分支的條件語句更快。 但是您的代碼很好。 我喜歡&& || 但這只是一個偏好,並不基於任何經驗。
var data = {a: 1, b: 2, c: 3};
var result = data.x ||
data.y && "y" ||
data.z && "z" ||
data.w && "w" ||
null;
我不想鍵入.hasOwnProperty。
編輯實際查看您的代碼后
var paintMode = data.regions || data.vpcs || data.zones || data.subnets || data.clusters || null;
if(paintNode) {
for(var i=0; i<paintMode.length; i++)
paintGroups(paintMode[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.