Talking about array algorithm slice

Posted by yarnold on Fri, 05 Jun 2020 18:17:28 +0200

As a whitespace that has just come into contact with js, you still don't know much about the methods in the array prototype.

Because you may like to change your character, you always like to dig deep into the low-level algorithm, so I'll share my slice() algorithm with you.

To write an algorithm, you have to look at what the function is trying to do, so you should test the function slice().

For example:

 //[No parameters passed
var arr = [1,5,3,4,6,9,4];

console.log(arr.slice());  //[1, 5, 3, 4, 6, 9, 4]
 //Pass a different type of parameter
console.log(arr.slice(undefined));//[1, 5, 3, 4, 6, 9, 4]
console.log(arr.slice(true));  //[5, 3, 4, 6, 9, 4]
console.log(arr.slice(-1));  //[4
console.log(arr.slice());  //[5, 3, 4, 6, 9, 4]]
console.log(arr.slice(NaN));//[1, 5, 3, 4, 6, 9, 4]
From the above, we can summarize some rules that in the function body, the function will use Number() function to convert the parameters in the parameter list to Number type, in order to complete the function cutting function;
So when we pass on two parameters, we know the rule, so I don't test it here, and I'm interested in doing it on my own.

Next, we can start writing algorithms

At first we need to be aware of the problem of passing functions in, because the slice() function can pass in multiple parameters, which is important to note, so we can't directly define the number of its parameters.
A clever way to do this is to let the function itself decide without setting the number of its parameters.
var a = Number(arguments[0]) ? arguments[0] : 0,//Set the default value of the first parameter to 0

b = Number(arguments[1]) ? arguments[1] : 0; //0 when parameter is NaN, undefined,false,null,'',''

So we solved the number of parameters, and here's the whole algorithm for the function

Array.prototype.slice = function() {

var that = this,arr = [],

a = arguments[0] ? (arguments[0]>=0 ? Math.floor(arguments[0]) : ((that.length - Math.abs(Math.ceil(arguments[0])))>0 ? (that.length - Math.abs(Math.ceil(arguments[0]))) : 0)) : 0,//Set the default value of the first parameter to 0

b = arguments[1] ? (arguments[1]>=0 ? Math.floor(arguments[1]) : ((that.length - Math.abs(Math.ceil(arguments[1])))>0 ? (that.length - Math.abs(Math.ceil(arguments[1]))) : 0)) : 0; //0 when parameter is NaN, undefined,false,null,'',''

if(arguments.length > 1){

for(var i = 0;i<(b-a) && i<that.length-a;i++){
//Consider truncating the length of the array here. If you only consider i<(b-a), it will occur when B-A is infinite and a>0; undefined will occur in the array

arr[i] = that[a+i];



for(var i = 0;i<that.length-a;i++){

arr[i] = that[a+i];



return arr;


If you have a better algorithm or understanding of this algorithm, you can share it with everyone. Thank you for watching!!