Home >Web Front-end >JS Tutorial >Correct use of splice() in Javascript

Correct use of splice() in Javascript

autoload
autoloadOriginal
2021-04-12 11:21:042066browse

Correct use of splice() in Javascript

1.splice() syntax

arrayObject.splice(index,deleteCount,item1,.....,itemX)
  • ##index : Specify the starting position of modification (counting from 0)

  • deleteCount: Indicates the number of array elements to be deleted.

  • item1,...,itemX: The elements to be added to the array start from the index position. If not specified, splice() will only remove array elements.

Return value: an array composed of the deleted elements. If only one element was removed, an array containing only one element is returned. If no elements were removed, an empty array is returned.

2. Usage example

Deleting array elements:


     <script>
          arr1=[9,2,6,4,5];
          res1=arr1.splice(2);
          console.log(res1);//[6, 4, 5]被删除的元素
          console.log(arr1);//[9,2]剩余元素

          arr2=[9,2,6,4,5];
          res2=arr2.splice(2,2);
          console.log(res2);//[6, 4]被删除的元素
          console.log(arr2);//[9,2,5]剩余元素
    </script>

Adding new array elements:


    <script>
          arr3=[9,2,6,4,5];
          console.log(arr3);
          result=arr3.splice(1,0,99,10);
        //   console.log(result);空数组
          console.log(arr3);
          result=arr3.splice(2,0,...[111]);
          console.log(arr3);
    </script>

Deleting array elements:

    <script>
          arr4=[1,2,3,4,5];
          res=arr4.splice(1,3,...[88,99,44]);
          console.log(arr4);
    </script>

Recommended: "

2021 js interview questions and answers (large summary)"

The above is the detailed content of Correct use of splice() in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to optimize Dom nodesNext article:How to optimize Dom nodes