zoukankan      html  css  js  c++  java
  • JavaScript : Array.splice() vs Array.slice()

    JavaScript : Array.splice() vs Array.slice()

    18 / FEB / 2015 BY VIVEK GARG 10 COMMENTS

    1. The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.

    2. The splice() method changes the original array and slice() method doesn’t change the original array.

    3. The splice() method can take n number of arguments:

    Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

    Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

    Argument 3…n: Optional. The new item(s) to be added to the array.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    var array=[1,2,3,4,5];
    console.log(array.splice(2));
    // shows [3, 4, 5], returned removed item(s) as a new array object.
     
    console.log(array);
    // shows [1, 2], original array altered.
     
    var array2=[6,7,8,9,0];
    console.log(array2.splice(2,1));
    // shows [8]
     
    console.log(array2.splice(2,0));
    //shows [] , as no item(s) removed.
     
    console.log(array2);
    // shows [6,7,9,0]
     
    var array3=[11,12,13,14,15];
    console.log(array3.splice(2,1,"Hello","World"));
    // shows [13]
     
    console.log(array3);
    // shows [11, 12, "Hello", "World", 14, 15]
     
               -5 -4 -3 -2 -1
                |  |  |  |  |
    var array4=[16,17,18,19,20];
                 |  |  |  |  |
                 0  1  2  3  4
     
    console.log(array4.splice(-2,1,"me"));
    // shows  [19]
     
    console.log(array4);
    // shows [16, 17, 18, "me", 20]

    If Argument(1) is NaN, it is treated as if it were 0.

    1
    2
    3
    4
    5
    6
    var array5=[21,22,23,24,25];
    console.log(array5.splice(NaN,4,"NaN is Treated as 0"));
    // shows [21,22,23,24]
     
    console.log(array5);
    // shows ["NaN is Treated as 0",25]

    If Argument(2) is less than 0 or equal to NaN, it is treated as if it were 0.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var array6=[26,27,28,29,30];
    console.log(array6.splice(2,-5,"Hello"));
    // shows []
     
    console.log(array6);
    // shows [26,27,"Hello",28,29,30]
     
    console.log(array6.splice(3,NaN,"World"));
    // shows []
     
    console.log(array6);
    // shows [26,27,"Hello","World",28,29,30]

    If Argument(1) or Argument(2) is greater than Array’s length, either argument will use the Array’s length.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var array7=[31,32,33,34,35];
    console.log(array7.splice(23,3,"Add Me"));
    // shows []
     
    console.log(array7);
    // shows [31,32,33,34,35,"Add Me"]
     
    console.log(array7.splice(2,34,"Add Me Too"));
    // shows [33,34,35,"Add Me"]
     
    console.log(array7);
    // shows [31,32,"Add Me Too"]

    4. The slice() method can take 2 arguments:

    Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

    Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var array=[1,2,3,4,5]
    console.log(array.slice(2));
    // shows [3, 4, 5], returned selected element(s).
     
    console.log(array.slice(-2));
    // shows [4, 5], returned selected element(s).
    console.log(array);
    // shows [1, 2, 3, 4, 5], original array remains intact.
     
    var array2=[6,7,8,9,0];
    console.log(array2.slice(2,4));
    // shows [8, 9]
     
    console.log(array2.slice(-2,4));
    // shows [9]
     
    console.log(array2.slice(-3,-1));
    // shows [8, 9]
     
    console.log(array2);
    // shows [6, 7, 8, 9, 0]

    If either argument is NaN, it is treated as if it were 0.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    var array3=[11,12,13,14,15];
    console.log(array3.slice(NaN,NaN));
    // shows []
     
    console.log(array3.slice(NaN,4));
    // shows [11,12,13,14]
     
    console.log(array3);
    // shows [11,12,13,14,15]

    If either argument is greater than the Array’s length, either argument will use the Array’s length

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var array4=[16,17,18,19,20];
    console.log(array4.slice(23,24));
    // shows []
     
    console.log(array4.slice(23,2));
    // shows []
     
    console.log(array4.slice(2,23));
    // shows [18,19,20]
     
    console.log(array4);
    // shows [16,17,18,19,20]

    I hope it helps, feel free to ask if you have any queries about this blog or our JavaScript and front-end engineeringservices.

    SyntaxSection

    array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
    

    ParametersSection

    start
    Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.
    deleteCount Optional
    An integer indicating the number of old array elements to remove.
    If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted.
    If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).
    item1, item2, ... Optional
    The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

    Return valueSection

    An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

    DescriptionSection

    If you specify a different number of elements to insert than the number you're removing, the array will have a different length at the end of the call.

    JavaScript Array: slice vs splice

    Feb 4, 2014 3 min read 

    xmen
    In JavaScript, mistaking slice for splice (or vice versa) is a common mistake among rookies and even experts. These two functions, although they have similar names, are doing two completely differentthings. In practice, such a confusion can be avoided by choosing an API that telegraphs the const-correctness of the function.

    Array’s slice (ECMAScript 5.1 Specification Section 15.4.4.10) is quite similar to String’s slice. According to the specification, slice needs to accept two arguments, start and end. It will return a new arraycontaining the elements from the given start index up the one right before the specified end index. It’s not very difficult to understand what slice does:

    'abc'.slice(1,2)           // "b"
    [14, 3, 77].slice(1, 2)    //  [3]
    

    An important aspect of slice is that it does not change the array which invokes it. The following code fragment illustrates the behavior. As you can see, x keeps its elements and y gets the sliced version thereof.

    var x = [14, 3, 77];
    var y = x.slice(1, 2);
    console.log(x);          // [14, 3, 77]
    console.log(y);          // [3]
    

    Although splice (Section 15.4.4.12) also takes two arguments (at minimum), the meaning is very different:

    [14, 3, 77].slice(1, 2)     //  [3]
    [14, 3, 77].splice(1, 2)    //  [3, 77]
    

    On top of that, splice also mutates the array that calls it. This is not supposed to be a surprise, after all the name splice implies it.

    var x = [14, 3, 77]
    var y = x.splice(1, 2)
    console.log(x)           // [14]
    console.log(y)           // [3, 77]
    

    When you build your own module, it is important to choose an API which minimizes this slice vs splice confusion. Ideally, the user of your module should not always read the documentation to figure out which one they really want. What kind of naming convention shall we follow?

    A convention I’m familiar with (from my past time involvement with Qt) is by choosing the right form of the verb: present to indicate a possibly modifying action and past participle to return a new version without mutating the object. If possible, provide a pair of those methods. The following example illustrates the concept.

    var p = new Point(100, 75);
    p.translate(25, 25);
    console.log(p);       // { x: 125, y: 100 }
     
    var q = new Point(200, 100);
    var s = q.translated(10, 50);
    console.log(q);       // { x: 200, y: 100 }
    console.log(s);       // { x: 210, y: 150 }
    

    Note the difference between translate() that moves the point (in 2-D Cartesian coordinate system) and translated() which only creates a translated version. The point object p changed because it calls translate. Meanwhile, the object q stays the same since translated() does not modify it and it only returns a fresh copy as the new object s.

    If this convention is used consistently throughout your application, that kind of confusion will be massively reduced. And one day, you can let your users sing I Can See Clearly Now happily!

    Related posts:

    ♡ this article? Explore more articles and follow me Twitter.

    Share this on Twitter Facebook

     

    comments powered by Disqus

  • 相关阅读:
    自动化测试-appium常用元素
    自动化测试-微信小程序
    自动化测试-环境搭建appium for windows
    安全测试-docker搭建sonar完成代码质量检测
    工具安装-pycharm使用已配置的虚拟环境
    安全测试-sonarscanner扫描代码
    工具安装-java集成到maven
    iOS 提升代码的安全性,可以做哪些措施???
    iOS 绘制一个表盘时钟,秒针效果可以“扫秒/游走”
    iOS 关于BTC 一些知识点
  • 原文地址:https://www.cnblogs.com/yasepix/p/10069181.html
Copyright © 2011-2022 走看看