This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge
Array access and traversal
1. Access array elements
Accessing an array element is as simple as “array name [subscript]”.
Var arr = new Array(3,4,5); console.log(arr[0]);Copy the code
2. Traversal group elements There are three types of traversal group elements: for,for in, and for of.
<script> var arr = new Array(3,4,5); For (var I =0; i<arr.length; i++){ console.log(arr[i]); } for(var I in arr){console.log(arr[I]); } for(var I of arr){console.log(I); } </script>Copy the code
Add, modify, and delete elements
1. Add elements
In JS, adding elements can be said to be very “capricious”!! The subscript can be larger than the length of the array. If the subscript is larger than the length of the array, the entire array will be larger, and the unassigned elements will be stored in empty locations.
Var arr = [1,2,3]; Obviously it has length 3, but you can add arr[4]=5; Arr = [1,2,3, 4]; // ArR has 5 elements. */ var arr = [1,2,3]; arr[4]=5; for(var i of arr){ console.log(i); }Copy the code
2. Modify elementsModifying an element is in the same form as adding an element, except that it updates the value for an existing element.
Var arr = [1, 2, 3]; For (var I of arr){console.log(I); } arr[1]=9; For (var I of arr){console.log(I); }Copy the code
3. Delete elementsDeleting an element requires the delete keyword, and only the element’s value is deleted; the element still occupies an empty storage location after deletion.
Var arr = [1, 2, 3]; delete arr[1]; for(var i of arr){ console.log(i); }Copy the code
Deconstruction assignment
What is deconstructive assignment? Let me give you an example to make sense
Var arr = [1, 2, 3]; var a,b,c; a=arr[0]; b=arr[1]; c=arr[2]; console.log(a); console.log(b); console.log(c);Copy the code
Var arr = [1, 2, 3]; var a,b,c; [a, b, c] = [1, 2, 3]. console.log(a); console.log(b); console.log(c);Copy the code
You will notice that the first code is obviously more cumbersome, but the results of both codes are the same, isn’t it amazing that this is where the JS destruct assignment comes in handy? When there are more elements on the left than on the right, the extra element will be assigned as undefined. When there are more elements on the right than on the left, the extra value on the right will be eliminated. In addition, deconstructive assignments can be used to exchange the values of two variables.
var n1=1,n2=2; [n1,n2] = [n2,n1]; // Another trickCopy the code
JS array above is some of the basic operation, if there are omissions or errors, welcome to leave a message to correct.