簡體   English   中英

在.splice()之后用角度函數重置數組的副本

[英]resetting a copy of an array in an angular function after .splice()

我要完成的工作是制作一個有角度的下拉菜單,從列表中刪除當前頁面。 加載下一個視圖時,我希望菜單重置並刪除當前的視圖。

組成下拉菜單的對象數組

var menuItems = [
    {menuItem: 'home', url: '/'},
    {menuItem: 'depth', url: '/depth'},
    {menuItem: 'bolt circle', url: '/bolt_circle'}
];

角度函數,對數組進行sort()和.slice()從數組中當前頁。

       $scope.sort = function(){
           $scope.items = menuItems;
           for(i=$scope.items.length-1; i>=0; i--){
               var obj = $scope.items[i];

           if($location.path() === obj.url){
               $scope.items.splice(i, 1);
            }
        }

我對angular和javascript很陌生,所以我並沒有建立連接為什么menuItems似乎是.splice()以及$ scope.items,每次我轉到頁面時,它都會從菜單中刪除,直到我沒有剩余的鏈接。 我本以為每次運行sort()函數時都會為數組創建一個副本,這會給我一個數組的全新副本。我希望我能對此做足夠的解釋。

執行此操作時:

$scope.items = menuItems;

不是在復制menuItems數組,而是在$scope Object中創建一個新屬性items ,該屬性items將具有 menuItems 相同的數組引用 這意味着$scope.itemsmenuItems相同。

為了創建menuItems數組的副本,您應該這樣做:

$scope.items = menuItems.slice(0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM