方法1:delete
在原数组上进行修改,将要删除位置的数据变成undefined,其他位置数据保持不动。适用于需要保持数组中元素位置的情况
test('delete syntax', function() {
var array = [1, 2, 3];
delete array[0];
notEqual(array, [2,3], 'delete fail?');
equal(array.length, 3, 'the element is still there');
equal(array[0], undefined, 'it has been change to undefined');
equal(array[1], 2, 'the original data is still there');
});
方法2:splice
在原数组上进行修改,将要删除位置后的数据前移,数组长度减少。据说在IE5.5版本前,splice方法的删除效果和delete相同,也是把相应位置的数据变成undefined,对于这种情况,请见方法3
test('splice syntax', function() {
var array = ['a', 'b', 'c'];
array.splice(0, 1);
deepEqual(array, ['b', 'c'], 'delete success');
equal(array.length, 2, 'the element has been removed');
equal(array[0], 'b', 'the original data has changed there position');
});
方法3:自定义函数
利用concat和slice方法组合,返回一个新的数组。
test('my delete function', function() {
/**
* 删除数组中的元素
*
* @param array
* @param index
* @return {array}
*/
function deleteArrayElement(/*array*/ array, /*int*/ index) {
if (index < 0 || index >= array.length) {
return array;
}
if (index == 0) {
array.shift();
} else if (index == (array.length - 1)) {
array.pop();
} else {
array = array.slice(0, index).concat(array.slice(index + 1, array.length));
}
return array;
}
var array = ['a', 'b', 'c', 'd'];
array = deleteArrayElement(array, 0);
deepEqual(array, ['b', 'c', 'd'], 'delete success');
equal(array.length, 3, 'the element has been removed');
equal(array[0], 'b', 'the original data has changed there position');
array = deleteArrayElement(array, 1);
deepEqual(array, ['b', 'd'], 'delete the 2nd');
array.push('e');
deepEqual(array, ['b', 'd', 'e'], 'add a new element');
array = deleteArrayElement(array, 2);
deepEqual(array, ['b', 'd'], 'delete the latst');
});
运行结果: