2014-12-24 181 views
0

這裏,我從json對象中刪除特定的Array [2]。但是,我在控制檯中看到的是 - 數組值是已刪除但它仍然在idx中,當我在刪除後使用jQuery中的$.each進行檢查時。那麼,如何以正確的方式刪除整個數組對象?從json對象中刪除json數組

var obj = { 
 
    equipments:'first', 
 
\t messages:['msg1','msg2','msg3'], \t 
 
} 
 

 
console.log(obj); 
 
$.each(obj.messages, function (idx, obj) { 
 
alert("before deleted index value" +idx); 
 
}); 
 

 
obj1 = obj; 
 

 
if(obj1["equipments"] == 'first') { 
 
     delete obj1.messages[2]; 
 
    } 
 
    
 
console.log(obj1); 
 
$.each(obj1.messages, function (idx, obj1) { 
 
alert("after deleted but index remains same" +idx); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

+0

同樣在這裏 - http://stackoverflow.com/questions/500606/javascript-array-delete-elements –

回答

1

當您使用delete陣列上它不會刪除索引,它設置elment到undefined但數組長度保持不變。

,因此會使用splice()但你也需要認識到,無論你做什麼,以obj1會發生obj也因爲obj1obj參考。這不是一個副本,當你做obj1=obj

+0

我該如何使用splice()?你能簡單解釋一下嗎?這將有所幫助 –

+1

'obj1.messages.splice(2,1);'第一個參數是開始索引,第二個是刪除多少元素 – charlietfl

+0

可以在這裏看到我的意思是關於從一個對象中刪除相同的另一個http ://jsfiddle.net/rs61z9gz/ – charlietfl

1

使用splice

obj1.messages.splice(2, 1); // at index 2, delete 1 element, inserting nothing 
+0

欣賞你的工作!但是,我不知道我需要刪除哪個索引。我喜歡比較值,根據比較,它會獲取特定的數組索引。然後,我正在刪除該數組。在這裏,您正在使用索引2刪除1個元素。刪除1意味着什麼?我知道索引是2 –

+0

如果你使用'splice(2,3,「f」,「g」)',它會刪除索引2,3和4(其中三個)的元素,並且插入'「f」 '和''g「'分別位於索引2和3。它還會將下列元素的所有索引更改爲-1,因爲我們插入的元素少於我們刪除的元素。如果您不知道需要刪除哪個索引,那麼您是如何管理'delete obj1.messages [2]'方法的,該方法還需要索引?找到索引,拯救世界。 – Amadan

+0

謝謝你的幫助!榮譽和@ charlietfl ..基於時間,我正在檢查他的答案。對不起!再次感謝! –

1

您當前的方法嘗試使用這樣的:

 $.each(obj1.messages, function (idx, obj1) { 
      if(typeof(obj1) != 'undefined')// log if the type of obj1 is not undefined because after delete the value will become undefined 
     console.log("after deleted but index remains same" +idx); 
     }); 

,你可以在這種情況下,它會使用拼接刪除索引它的自我是這樣的:

if(obj1["equipments"] == 'first') { 
      obj1.messages.splice(2, 1); 
      } 

    $.each(obj1.messages, function (idx, obj1) { 
     console.log("after deleted index " +idx); 
     }); 
+0

欣賞你的作品! –