2013-04-11 87 views
1

我有這樣的代碼:JavaScript的循環重新評估每次迭代導致問題

var app = { 
    items: [ 
     [{ 
      title: 'Overview', 
      id: 'dashboard' 
     }, { 
      title: 'Reports', 
      id: 'reports' 
     }], 
     [{ 
      title: 'Customers', 
      id: 'customers' 
     }, { 
      title: 'Quotes', 
      id: 'quotes' 
     }, { 
      title: 'Sales', 
      id: 'sales' 
     }], 
     [{ 
      title: 'Suppliers', 
      id: 'suppliers' 
     }, { 
      title: 'Purchases', 
      id: 'purchases' 
     }], 
     [{ 
      title: 'Bank', 
      id: 'bank' 
     }, { 
      title: 'Projects', 
      id: 'projects', 
      disabled: true 
     }, { 
      title: 'Journal', 
      id: 'journal', 
      disabled: true 
     }] 
    ] 
} 

var userDetails = { 
    IsAdmin: true 
}; 

for (var x = 0; x < app.items.length; x++) { 
    app.items[x].filter(function (items) { 
     if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) { 
      var ind = app.items[x].indexOf(items); 
      app.items[x].splice(ind, 1); 
     } 
    }); 
} 

console.log(app.items); 

的輸出是有左每個陣列由端在1個對象。這是不希望的,通過我的計算,應該只是左(引號對象)一個對象,

相關的jsfiddle:http://jsfiddle.net/UdzEW/

任何想法?

+1

不要修改'filter'回調裏面你的陣列。 – akonsu 2013-04-11 11:19:07

+1

您正在濫用['.filter()'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter)方法 – Andreas 2013-04-11 11:20:02

+0

請務必記住'filter '一般來說,舊版瀏覽器不支持'。 – iMoses 2013-04-11 11:43:44

回答

3

.filter的想法是,你提供一個函數tahat返回一個布爾值,它決定了值應該留下還是去;它不應該在原地修改數組。

var filtered = app.items[x].filter(function (items) { 
    if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) { 
     return false; 
    } 
    return true; 
}); 

filtered內容現在應該包含只有那些失敗內條件項的新數組。

0

試試這個:

for (var x = 0; x < app.items.length; x++) { 
    app.items[x] = app.items[x].filter(function (items) { 
     return !(items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')); 
    }); 
    !app.items[x].length && app.items.splice(x--, 1); 
} 

返回[[Array(1)]]的 「行情」 對象