[Code sea shell JS] JS: delete elements in the array, sea shell js

Source: Internet
Author: User
Tags javascript array

[Code sea shell JS] JS: delete elements in the array, sea shell js
Preface

To delete an element from a list in Java, you can simply use the remove Method.

The array in js does not have the remove method, but in js, the array has the splice method to achieve the same effect. In addition, you can also use other methods to achieve this effect.


Use the splice method to delete elements from the array

First, let's take a look at how to use the splice method.

Syntax

arrayObject.splice(index,howmany,item1,.....,itemX)
Parameters Description
Index Required. Integer that specifies the position of the added/deleted project. A negative number can be specified from the end of the array.
Howmany Required. The number of projects to delete. If it is set to 0, the project will not be deleted.
Item1,..., itemX Optional. Add a new project to the array.


Note that this method will change the original array.

Simplest example: -- delete an element from an array

<script>var array1 = ["name1","name2","name3","name4"];array1.splice(1,1);alert(array1);</script>

Output: name1, name3, name4

Resolution:

1. splice ()-delete the second element.

The first 1 is the position, starting from 0, which is hard to understand;

The second one is the number. delete an element.

2. the array value of the method array does not need to be array1 = XXX. The reason is also described above.


Continue, if you want to add an element at the same time as the deletion location:

<script>var array1 = ["name1","name2","name3","name4"];array1.splice(1,1,"name5");alert(array1);</script>

Output: name1name5, name3, name4



Delete elements from a complex array

The elements in the array in the preceding example are general strings.

The so-called complex array here refers to the element in the exponent group being an object rather than a simple string.

Before getting started, write a method to convert js array into str:

function arrayToString(array){var str = "";if(array!=null&&array.length>0)    {    str += "[";for(var i=0;i<array.length;i++)    {   var objStr = "";   objStr += "{";   var obj = array[i];   for(var key in obj)   {        objStr += key;objStr += ":'";objStr += obj[key];objStr += "'";objStr += ",";   }   if(objStr.length>3)   {  objStr = objStr.substring(0,objStr.length-1);   }    objStr += "}";   str += objStr;   if(i<array.length-1)   {  str += ",";   }}str += "]";}return str;}

Next, delete an array element whose element type is object.

<script>var obj1 = {key:"key1",name:'name1_1'};var obj2 = {key:"key2",name:'name1_1'};var obj3 = {key:"key3",name:'name2_2'};var obj4 = {key:"key4",name:'name2_2'};var array1 = [obj1,obj2,obj3,obj4];//delete by keyvar delKey = "key2";for(var i=0;i<array1.length;i++){var keyTemp = array1[i].key;if(keyTemp===delKey)    {array1.splice(i,1);}}alert(arrayToString(array1));</script>

Note:

1. The key here is unique, and the name value is not

2. Here, the array loop does not use forEach because IE does not support

For details, see:

3. The preceding elements are used to delete unique key values.

ForEach of Javascript Array Traversal


In general, only one element is deleted at a time. What if multiple elements are deleted at a time?

It is similar to deleting an element whose name value is "name1_1". It corresponds to two elements, and the syntax should be:

<script>var obj1 = {key:"key1",name:'name2_2'};var obj2 = {key:"key2",name:'name2_2'};var obj3 = {key:"key3",name:'name1_1'};var obj4 = {key:"key4",name:'name1_1'};var array1 = [obj1,obj2,obj3,obj4];//delete by namevar delName= "name2_2";for(var i=0;i<array1.length;i++){var nameTemp = array1[i].name;if(nameTemp===delName)    {array1.splice(i,1);}}alert(arrayToString(array1));</script>

However, the above statements are incorrect.

It should be because the length of array1 changes after an element is deleted for the first time, and the elements corresponding to each position also change.

Therefore, the above statement is as follows:

1. An error is reported, indicating that the specified element cannot be found.

2. Either the execution result is incorrect. This is the case in the above example.


To address this problem, you can think of the following solutions:

1. delete one at a time, multiple cycles

2. Another method is to create a new array, put the elements that do not need to be deleted into this array, and replace the old array with this array.



Js deletes array elements

Var arr = [1, 2, 3, 4, 5];
// Original array
Alert ("original array:" + arr); // 1, 2, 3, 4, 5
// Delete and return the first element
Alert ("execute arr. shift () and return:" + arr. shift (); // 1
Alert ("array:" + arr); // 2, 3, 4, 5
// Delete and return the last element
Alert ("execute arr. pop () and return:" + arr. pop (); // 5
Alert ("array:" + arr); // 2, 3, 4
// Add one or more elements at the beginning of the array to return the new length of the array.
Alert ("execute arr. unshift ('one') and return:" + arr. unshift ("one"); // 4
Alert ("array:" + arr); // one, 2, 3, 4
// Add one or more elements at the end of the array to return the new length of the array.
Alert ("execute arr. push ('end') and return:" + arr. push ("end"); // 5
Alert ("array:" + arr); // one, 2, 3, 4, end
// Delete n elements from position I.
Arr. splice (0, 1 );
Alert ("execute arr. splice (0, 1 )");
Alert ("array:" + arr); // 2, 3, 4, end
// Delete n elements from position I and insert s elements into the position
Arr. splice (0, 0, "one ");
Alert ("execute arr. splice (0, 0, 'one ')");
Alert ("array:" + arr); // one, 2, 3, 4, end

Www.w3school.com.cn/js/jsref_obj_array.asp

Js deletes the element of a specified value (not a specified position) from the array.

If you do not use a third-party framework, a similar extension function can return the subscript of an element based on the specified value. You can only search for the element and then delete it.

<Script type = "text/javascript">
Array. prototype. indexOf = function (val ){
For (var I = 0; I <this. length; I ++ ){
If (this [I] = val) return I;
}
Return-1;
};
Array. prototype. remove = function (val ){
Var index = this. indexOf (val );
If (index>-1 ){
This. splice (index, 1 );
}
};

Var array = [1, 2, 3, 4, 5];
Array. remove (3 );

</Script>

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.