2010-01-21 26 views

Trả lời

13

Các "xóa" không thay đổi mảng, nhưng các yếu tố trong mảng:

# x = [0,1]; 
# delete x[0] 
# x 
[undefined, 1] 

gì bạn cần là array.splice

5

bạn phải sử dụng array.splice - xem http://www.w3schools.com/jsref/jsref_splice.asp

myarray.splice(0, 1); 

này sau đó sẽ loại bỏ các yếu tố đầu tiên

+2

vâng. Mã khác cũng loại bỏ mục đó. Nhưng nó không cập nhật độ dài. –

1

Theo this docs các nhà điều hành xóa không làm thay đổi chiều dài ofth earray. Bạn có thể sử dụng mối nối() cho điều đó.

1

Từ MDC tài liệu Array Avatar của:.

"Khi bạn xóa một phần tử mảng, chiều dài mảng không bị ảnh hưởng Đối với Ví dụ, nếu bạn xóa một [3], a [4] là vẫn a [4] và [3] không xác định. Điều này giữ ngay cả khi bạn xóa phần tử cuối cùng của mảng (xóa a [a.length-1]). "

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array

0

Đó là hành vi bình thường. Hàm delete() không xóa chỉ mục, chỉ nội dung của chỉ mục. Vì vậy, bạn vẫn có 2 phần tử trong mảng, nhưng tại chỉ số 0 bạn sẽ có undefined.

1

Bạn có thể làm điều này với phương pháp John Resig 's đẹp remove():

Array.prototype.remove = function(from, to) { 
    var rest = this.slice((to || from) + 1 || this.length); 
    this.length = from < 0 ? this.length + from : from; 
    return this.push.apply(this, rest); 
}; 

hơn

// Remove the second item from the array 
array.remove(1); 
// Remove the second-to-last item from the array 
array.remove(-2); 
// Remove the second and third items from the array 
array.remove(1,2); 
// Remove the last and second-to-last items from the array 
array.remove(-2,-1);