On the slice method of using native JS to implement array

Source: Internet
Author: User
Tags array length

The slice method has these situations: does not pass the parameter, passes a parameter, passes two parameters. and the arguments support negative numbers, the effect of each case is not said here.

The core method is to iterate through the array of calls to this method through a for loop, place the contents to be removed into the new array, and return the new array.

All the conditions of processing judgment, all for the sake of the loop can be executed correctly

This was written a long time ago, although the 8 lines of code, but the ternary operator too many, and no parentheses, now look back to see really eyeful of the stars.

Array.prototype._slice = function _slice () {
var n1 = number (Arguments[0]), N2 = Arguments[1], n3 = [];
N2 = N2 = = = undefined? This.length:Number (n2)? Number (N2): 0;
N2 = N2 < 0? Math.Abs (n2) > This.length && n2 >-1? 0:this.length + Math.ceil (n2): n2 > This.length? This.length:Math.floor (N2);
N1 = n1? N1 < 0? Math.Abs (n1) > This.length | | N1 >-1? 0:this.length + Math.ceil (n1): N1 > This.length? This.length:Math.floor (N1): 0;
for (var i = n1; I < N2; i++) {
N3[n3.length] = this[i];
}
return n3;
};

So the above code looks at it, so let's start by analyzing the For loop, because all the conditional judgments are handled around this loop, and it's easy to understand what the conditions of the next parsing are for.

i = n1 defines the starting position (which contains the position of the N1)

I < N2 define the end position (which does not include the position of the N2)

This loop sets where to start and where to end , so we just have to deal with the values of N1 and N2 so that we can meet all the communication parameters.

For loop analysis completed, there is no good analysis, now a row of split analysis code.

Because the personal expression ability is limited, some words more want to express clearly the more the expression is unclear, think the text in the bottom box is too wordy, can not see or selectively ignore, or only see the red part of the Mark .

First line:
var n1 = number (Arguments[0]), N2 = Arguments[1], n3 = [];

Two variables n1 and N2 are used to receive the two parameters in the arguments, which can be used to determine the data of the transmission.

The use of N3 for the time being.

Because arguments is an array of classes is also an object, if when arguments[0] or arguments[1] does not exist, it will not be an error, but the default is undefined

Second line:
N2 = N2 = = = undefined? This.length:Number (n2)? Number (N2): 0;

If you feel that the above ternary operator is difficult to understand, you can look at the following with if write

    if (N2 = = = undefined        ) {this.    length; Else if (Number (N2)) {        = number (n2);     Else {        = 0;    }
The second line of code _if

Use N2 to determine whether a second parameter has a value.

    • If it is undefined, the value is not passed.

At this time, it is already possible to determine whether the external run execution Code is slice () or slice (X)

Here, if you want to: "To determine whether the first parameter has a value, if there is a value to return the corresponding item in the array, no value will return all items", is not incorrect, and the code of this article idea is somewhat different, we do not care whether the second parameter has a value in the pass, the value passed in is a valid value, We all have to determine a valid value for the second parameter.

This is to integrate all possible branches into one branch, to the last unified disposable processing. That is: regardless of what the pass may be, we will only process it once in the For loop at the end of the code, and we'll just return it once.

In the case of no value, it means that the user needs the following: starting at the position specified in the array and intercepting to the end .

So we're going to assign this parameter: This.length.

This represents an array of calls to the _slice method, and the this.length is naturally the length of the array.

In the case where the second argument is empty or invalid, the representation starts at the location of the N1 and takes out all the contents that follow the array.

    var ary = [1,2,3,4,5,6]    ary.slice (1)// here means starting from the first position of the array, removing all remaining items    / / results [2,3,4,5,6]

Here in the For loop, N1 is equal to 1, N2 equals 5.

Because the value of N1 is not yet processed, we don't know how much N2 is. So the first assignment this.length, this value is more than the actual required value, so do not worry about not enough to take the situation

Given more of course also not, so need to be in the back to deal with this situation.

    • If not undefined, the value is passed in, and the number () method is used to force the conversion, guaranteeing validity.

If a number is passed in, assign it to N2.

If the passed in parameter is not a standard number will be processed as number or Nan, if it is Nan, the N2 is assigned a value of 0, indicating that an item is not taken out (processed according to the built-in slice results)

Third line:
N2 = N2 < 0? Math.Abs (n2) > This.length && n2 >-1? 0:this.length + Math.ceil (n2): n2 > This.length? This.length:Math.floor (N2);

If you feel that the above ternary operator is difficult to understand, you can look at the following with if write

 if  (N2 < 0 if  (Math.Abs (n2) > this . Length && n2 > -1 = 0 else   {n2  = this . Length + Math.ceil (n2); }}  else  if  (N2 > this  .length) {n2  = this.length;  else  {n2  = Math.floor (n2); }
The third line of code _if
    • If N2 is negative, the end position is calculated from the end of the array, such as:
    •     var ary = [1,2,3,4,5];    Ary.slice (/ /The output is [up]    // End is counted from the end, that is, starting from the No. 0 position, to the 3rd (not included)

When N2 is less than 0 and N2 >-1, that is, N2 is a negative decimal of fraction, an empty array is returned, so N2 is assigned a value of 0

When N2 is less than 0 and the absolute value of N2 is larger than the array length, an empty array is returned, so the N2 is assigned a value of 0

Do not ask why so deal with, here is according to the official built-in slice method results processing, ha ha ~

When N2 is less than 0, why is the remaining case This.length + Math.ceil (n2)?

Because a negative number corresponds to a positive position, the array length + negative number is used to calculate

For example, in the above code, slice (0,-3), equivalent to slice (0,2)

Why do you use Math.ceil (n2)?

Encountered decimal up rounding

When 0 < N2 < This.length, automatic down rounding, so Math.floor (n2)

When N2 is greater than the array length, all entries after the start position are returned, so the N2 is assigned a value this.length

The same procedure, based on the results returned by the built-in slice method.

At this point, the second parameter has been processed in all cases.

last line (not counted for loop):
N1 = n1? N1 < 0? Math.Abs (n1) > This.length | | N1 >-1? 0:this.length + Math.ceil (n1): N1 > This.length? This.length:Math.floor (N1): 0;

If you feel that the above ternary operator is difficult to understand, you can look at the following with if write

    if(N1) {if(N1 < 0) {            if(Math.Abs (N1) > This. length | | N1 >-1) {N1= 0; } Else{N1= This. length +Math.ceil (N1)}} Else if(N1 > This. Length) {N1= This. Length; } Else{N1=Math.floor (N1)}} Else{N1= 0; }
last line of code _if

N1 's handling is relatively straightforward.

When N1 is false, the entire array is returned, so the N1 is assigned a value of 0

When N1 is negative, and the absolute value of N1 is greater than this.length, the entire array is returned, so the N1 is assigned a value of 0

When N1 is negative, and N1 is less than-1, which is the negative fraction decimal, the entire array is returned, so N1 is assigned a value of 0

The remainder of the N1 is a negative range, with This.length + Math.ceil (N1) to deal with the value of N1, where the situation and the above N2, do not repeat

When N1 is greater than this.length, it is taken from the end of the array, so it is assigned a value of N1 this.length

Next, the only time left This.length >= n1 > 0, all downward rounding (for decimals), so N1 assignment Math.floor (N1)

Why did you do it?

Judging by the results returned by slice

The rest of the for loop has been mentioned at the beginning, and the role of N3 is not to say much, but what is in it is to remove the content from the function that executes the method.   Although the space is slightly more, but in fact the idea is very simple, is to deal with the value of two formal parameters, but only a limited style of writing can expect to use more words to express the idea of the mind, temporarily still can not do sharply clear expression. If the code is wrong or the original slice there is a difference between the place , but also hope that the message reminds me, I will change the first time, in advance thank you!   at the same time, I also seriously do not recommend wasting time reading these words, probably understand the idea and then through their own a little bit of trying to summarize their own methods, more than here to eat a lot stronger, the code is not valuable, the key is thinking, more hands-on brain is the most useful . again, the understanding and expression is really different, want to complete the heart of the thought of the expression seems to need to write a more write, write a rough hope you don't too mind ...

On the slice method of using native JS to implement array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.