移动元素函数里判断over<0的情况i应该从startIdx+delCount+over开始/**数组splice方法实现arr.splice(startIdx,delCount,add1,add2,...);*/Array.prototype._splice=function(){//1. 记录入参个数letargumentsLen=arguments.length;letstart=arguments[0],deleteCount=arguments[1];//2. 数组长度letarrayLength=this.length;letarr=Object(this);//3. 添加元素个数letaddCount=argumentsLen>2 ? argumentsLen-2 : 0console.log('addCount: ',addCount);//4. 计算有效的开始位置startletstartIdx=computeSpliceStartIdx(start,arrayLength);//5. 计算有效的删除个数letdelCount=computeSpiceDelCount(startIdx,deleteCount,arrayLength);console.log('delCount: ',delCount);//6. 记录删除的元素letdelElements=newArray(delCount);recordDelElements(startIdx,delCount,arr,delElements);//7. 判断是否是密封对象if(delCount!==addCount&&Object.isSealed(arr)){thrownewTypeError('the arr is sealed')}//8. 判断是否是冻结对象if(delCount>0&&addCount>0&&Object.isFrozen(arr)){thrownewTypeError('the arr is frozen')}//移动数组元素moveElements(startIdx,delCount,arr,addCount);leti=startIdx;letargumentsIdx=2;//插入新的元素while(argumentsIdx<argumentsLen){arr[i++]=arguments[argumentsIdx++];}arr.length=arrayLength-delCount+addCount;returndelElements;}functioncomputeSpliceStartIdx(start,arrayLength){if(start<0){start+=arrayLength;returnstart<0 ? 0 : start;}//start>0的情况returnstart>arrayLength-1 ? arrayLength-1 : start;}//计算delCountfunctioncomputeSpiceDelCount(startIdx,deleteCount,arrayLength){if(deleteCount>arrayLength-startIdx){deleteCount=arrayLength-startIdx}if(deleteCount<0)deleteCount=0returndeleteCount;}//记录删除的元素functionrecordDelElements(startIdx,delCount,arr,delElements){for(leti=0;i<delCount;i++){delElements[i]=arr[startIdx+i];}}//移动数组functionmoveElements(startIdx,delCount,arr,addCount){letover=addCount-delCount;console.log('over: ',over);if(over>0){//增加的数大于了删除的数 向后移动for(leti=arr.length-1;i>=startIdx+delCount;i--){arr[i+over]=arr[i];}}elseif(over<0){//增加的数小于删除的数 向前移动for(leti=startIdx+delCount+over;i<=arr.length-1;i++){if(i+Math.abs(over)>arr.length-1){deletearr[i]continue}arr[i]=arr[i+Math.abs(over)];}console.log('arr: over<0',arr);}}letarr=[1,2,3,4,5];arr._splice(1,3,6,7)console.log('arr: ',arr);//arr: [ 1, 6, 7, 5 ]Originally posted by @xllpiupiu in #138 (comment)
Originally posted by @xllpiupiu in #138 (comment)