Home > Web Front-end > JS Tutorial > body text

Correct use of splice() in Javascript

autoload
Release: 2021-04-12 11:21:04
Original
1996 people have browsed it

Correct use of splice() in Javascript

1.splice() syntax

arrayObject.splice(index,deleteCount,item1,.....,itemX)
Copy after login
  • ##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>
Copy after login

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>
Copy after login

Deleting array elements:

    <script>
          arr4=[1,2,3,4,5];
          res=arr4.splice(1,3,...[88,99,44]);
          console.log(arr4);
    </script>
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!