在數組元素上使用delete
運算符與使用Array.splice
方法有什麼Array.splice
? 數組
例如: ide
myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // or myArray.splice (1, 1);
若是能夠像刪除對象同樣刪除數組元素,爲何還要使用splice方法? ui
在嘗試瞭解如何從數組中刪除元素的每次出現時,我偶然發現了這個問題。 這裏有一個比較的splice
和delete
去除每個'c'
從items
陣列。 spa
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']; while (items.indexOf('c') !== -1) { items.splice(items.indexOf('c'), 1); } console.log(items); // ["a", "b", "d", "a", "b", "d"] items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']; while (items.indexOf('c') !== -1) { delete items[items.indexOf('c')]; } console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
若是要迭代一個大數組並有選擇地刪除元素,則每次刪除都調用splice()會很昂貴,由於splice()每次都必須從新索引後續元素。 因爲數組在Javascript中是關聯的,所以刪除單個元素而後再從新索引數組會更有效。 .net
您能夠經過構建一個新數組來作到這一點。 例如 code
function reindexArray( array ) { var result = []; for( var key in array ) result.push( array[key] ); return result; };
可是我認爲您不能修改原始數組中的鍵值,這樣作會更有效-看起來您可能必須建立一個新數組。 對象
請注意,您不須要檢查「未定義」條目,由於它們實際上並不存在,而且for循環不會返回它們。 這是陣列打印的結果,將其顯示爲未定義。 它們彷佛不存在於內存中。 索引
若是您可使用諸如slice()之類的更快的方法,可是它不會從新索引,那將是很好的。 有人知道更好的方法嗎? ip
實際上,您可能能夠按如下方式進行,這可能會更高效,更明智地執行如下操做: 內存
reindexArray : function( array ) { var index = 0; // The index where the element should be for( var key in array ) // Iterate the array { if( parseInt( key ) !== index ) // If the element is out of sequence { array[index] = array[key]; // Move it to the correct, earlier position in the array ++index; // Update the index } } array.splice( index ); // Remove any remaining elements (These will be duplicates of earlier items) },
值得一提的是,拼接僅適用於數組。 (不能依賴對象屬性遵循一致的順序。)
要從對象中刪除鍵值對,刪除其實是您想要的:
delete myObj.propName; // , or: delete myObj["propName"]; // Equivalent.
你能夠用這樣的東西
var my_array = [1,2,3,4,5,6]; delete my_array[4]; console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]
splice
將與數字索引一塊兒使用。
而delete
能夠用於其餘類型的索引。
例:
delete myArray['text1'];