读老道(Douglas Crockford)的《Javascript:The Good Parts》中关于array.splice()方法的实现代码,现在自己加一些注释。
//array.splice() is a method that delete some items in an array, //and add new items to the place where the deleted items used //to be, finally, it returns the deleted items as an array. Array.method('splice', function (start, deleteCount) { var max = Math.max, min = Math.min, delta, element, //arguments here refer to all the arguments this method //receive(as an array). So we should drop the first two //paramaters(start and deleteCount). insertCount = max(arguments.length - 2, 0), k = 0, len = this.length, new_len, result = [], shift_count; //if start is null, start = 0. start = start || 0; //if start is a negtive number, add start and len to get the //index of the start element. if (start < 0) { start += len; } //make sure that start is no bigger than len nor smaller than 0. start = max(min(start, len), 0); //if deleteCount is not given, delete all the elments after start. //And make sure it is is no bigger than len nor smaller than 0. deleteCount = max(min(typeof deleteCount === 'number' ? deleteCount : len, len − start), 0); delta = insertCount − deleteCount; new_len = len + delta; //push this[start,start + deleteCount -1] into result, namely just //set the deleted array that will be returned. while (k < deleteCount) { element = this[start + k]; if (element !== undefined) { result[k] = element; } k += 1; } //shift_count is the count of remained elements in this[start,] shift_count = len - start - deleteCount; //set the new index of the elements left in this[start,]. if (delta < 0) { k = start + insertCount; while (shift_count) { this[k] = this[k − delta]; k += 1; shift_count −= 1; } this.length = new_len; } else if (delta > 0) { k = 1; while (shift_count) { this[new_len − k] = this[len − k]; k += 1; shift_count −= 1; } } //push the added items in the new index-aranged array. for (k = 0; k < insertCount; k += 1) { this[start + k] = arguments[k + 2]; //just return the result,nail it! return result; });