Examples of using JavaScript Array.prototype.slice _javascript tips

Source: Internet
Author: User
Tags javascript array
Often, you can see Array.prototype.slice (arguments, 0); This method can be used in function () {}, which converts the argument list of functions to a true array. Take a look at an example:
Copy Code code as follows:

var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
(function () {
var args = arguments;
Console.log (args, Tostring.call (args)); [1, 2, 3] "[Object Arguments]"
var Argsarr = slice (args, 0);
Console.log (Argsarr, Tostring.call (Argsarr)); [1, 2, 3] "[Object Array]"
} (1,2,3))

We can see the parameter list of the function arguments through the slice call, a second variable array.
Similarly, you can convert a selected DOM element to an array:
Copy Code code as follows:

Slice.call (Document.queryselectorall ("div"));

Let's see if the slide method can convert an object to an array. Take a look at the example:
Copy Code code as follows:

Console.log (Slice.call (' string ')); ["S", "T", "R", "I", "N", "G"]
Console.log (Slice.call) (New string (' string ')); ["S", "T", "R", "I", "N", "G"]

Each time, the string is converted directly into an array.
However, the number, Boolean value, is converted to an empty array:
Copy Code code as follows:

Console.log (Slice.call (33));
Console.log (Slice.call (true));

A normal object is also converted to an empty array unless you add a length attribute to it:
Copy Code code as follows:

Console.log (Slice.call ({name: ' obj '})); // []
Console.log (Slice.call ({0: ' zero ', 1: ' One '}); // []
Console.log ({0: ' zero ', 1: ' One ', Name: ' obj ', length:2}); ["Zero", "one"]

Also, it can be used to clone arrays:
Copy Code code as follows:

var Srcarr = [1,2,3];
var newArr = srcarr.slice (0);
Console.log (Srcarr, NEWARR); [1,2,3] [1,2,3]
Console.log (Srcarr = = NEWARR); False
Related Article

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.