手写Array.prototype.push
May 24, 2020
前端知识复习 code snippet
- t O be ? ToObject(this value).
- Let len be ? LengthOfArrayLike(O).
- Let items be a List whose elements are, in left to right order, the arguments that were passed to this function invocation.
- Let argCount be the number of elements in items.
- If len + argCount > 253 - 1, throw a TypeError exception.
Repeat, while items is not empty,
- Remove the first element from items and let E be the value of the element.
- Perform ? Set(O, ! ToString(len), E, true).
- Set len to len + 1.
- Perform ? Set(O, "length", len, true).
- Return len.
代码
Array.prototype.myPush = function(){
var O = Object(this);
var len = O.length >>> 0;
var argCount = arguments.length;
// argCount or len may exceed MAX_SAFE_INTEGER, therefore argCount+len may not be safe
// do not use argCount + len > Number.MAX_SAFE_INTEGER
if(argCount > Number.MAX_SAFE_INTEGER - len){
throw TypeError('Invalid array length')
}
for(var k=0;k<argCount;k++){
O[len+k] = arguments[k];
};
len = len + argCount;
O.length = len;
return len;
}