Home > php教程 > PHP开发 > body text

A brief discussion on precautions when using the splice function to delete elements in an array

高洛峰
Release: 2017-01-03 16:15:29
Original
1247 people have browsed it

Things to note when using the splice function to delete elements in an array

Delete elements with value c:

<script>
var arr = new Array();
arr[0] = &#39;a&#39;;
arr[1] = &#39;b&#39;;
arr[2] = &#39;c&#39;;
arr[3] = &#39;c&#39;;
arr[4] = &#39;e&#39;;
 
for(var i=0; i<arr.length; i++){
  if(arr[i] == &#39;c&#39;){
    arr.splice(i,1);
    i=i-1;  // 必须对i减去1,否则后面的一个元素会被跳过去
  }
 
}
</script>
Copy after login

Note : If you use for(i in arr), the following element will always be skipped

<script>
 
var arr = new Array();
arr[0] = &#39;a&#39;;
arr[1] = &#39;b&#39;;
arr[2] = &#39;c&#39;;
arr[3] = &#39;c&#39;;
arr[4] = &#39;e&#39;;
 
for(i in arr){
 
  if(arr[i] == &#39;c&#39;){
    arr.splice(i,1);
    i=i-1;  // 这行代码无效,i 的值并不会改变
 
  }
  alert(arr.length);
}
</script>
Copy after login

The above article briefly talks about using the splice function to Things to note when deleting elements are all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more brief discussion on the precautions when using the splice function to delete elements in an array, please pay attention to the PHP Chinese website for related articles!


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template