当前位置:网站首页>Array methods and loops in JS
Array methods and loops in JS
2022-07-27 02:24:00 【It's Xiaofei hey】
JS Common properties of arrays :length
length Is a readable and writable property , Used to represent the length of the array ( That is, the number of array elements ). By visiting length attribute , You can get the length of the array ; And by modifying length Value , You can increase or decrease array elements , You can even completely empty array elements .
length Attribute reading 、 Examples of write operations are as follows :
var arr = [1,2,3];
alert(arr.length);// Read array length , The result is 3
arr.length = 1;// Modify the length of the array to 1, At this point, only the first element of the array remains
arr.length = 0;// Quickly empty the array , There are no elements in the array at this time notes : Quick emptying can be done by modifying length The property value is 0 Outside , Another way is to use code :arr=[]. If arr There are many original elements , Then use arr=[] The method of emptying the array is more efficient than modifying length The property value is 0 The method is higher .
JS A common method for arrays
Arrays provide some common methods , You can add array elements 、 Delete 、 Functions such as replacement and sorting .
1) push( Elements 1,…, Elements n)
push() Method can add the elements specified by the parameter to the end of the array in turn , And return the array length after adding elements ( The method must have at least one parameter ).
3) pop() Delete array end element
4) shift() Delete the array header element
shift() Method to delete the first element of the array , And return the deleted element .
5) splice(index,count[, Elements 1,…, Elements n])
splice() Examples of the functions implemented by the method are as follows .
① Use splice() Deletes the specified number of elements from the specified location
② Use splice() Replace the specified number of elements starting from the specified position with the specified element
③ Use splice() Add the specified element at the specified location
sort()、sort(compareFunction)
var arr = [1,2,3];
alert(arr.push(4));// Returns the length of the final array :4
alert(arr);// return :1,2,3,4
alert(arr.push(5,6,7));// Returns the length of the final array :7
alert(arr);// return :1,2,3,4,5,6,7
2) unshift( Elements 1,…, Elements n)
//unshift() Method can add the elements specified by the parameter to the front of the array in turn , And return the array length after adding elements . The method must have at least one parameter . Be careful :IE6、IE7 The return value of method is not supported . Examples are as follows :
var arr = [1,2,3];
alert(arr.unshift('a'));// Returns the length of the final array :4
alert(arr);// return :a,1,2,3
alert(arr.unshift('b','c','d'));// Returns the length of the final array :7
alert(arr);// return :b,c,d,a,1,2,3
//pop() Method to pop up ( Delete ) The last element of the array , And return the pop-up element . Examples are as follows :
var arr = ['A','B','C','D'];
alert(arr.pop());// return :D
alert(arr);// return :A,B,C
var arr = ['A','B','C','D'];
alert(arr.shift());// return :A
alert(arr);// return :B,C,D
//splic() The function of the method is relatively strong , It can delete a specified number of elements 、 Replace the specified element and add the element at the specified position . The realization of these different functions needs to be determined in combination with method parameters :
// When the parameters are only index and count For two parameters , If count It's not equal to 0,splice() Method to realize the deletion function , At the same time, the deleted element is returned : from index Start deletion at the position specified by the parameter count Parameter specifies the number of elements ;
// When the parameter is 3 More than , And count Parameters for 0 when ,splice() Method to implement the replacement function , At the same time, return the replaced element : Replace... With the third and subsequent arguments index Parameter specifies the start of the location count Parameter specifies the number of elements ;
// When the parameter is 3 More than , And count Parameter is 0 when ,splice() Method to add functions : Add to... With the third and subsequent parameters index Parameter at the specified location .
var arr = ['A','B','C','D'];
//2 Parameters , The second parameter is not 0, Realize the deletion function
alert(arr.splice(0,2));
alert(arr); // return C,D
var arr = ['A','B','C','D'];
//3 Parameters , The second parameter is not 0, Implement the replacement function : use a Replace A, return :A
alert(arr.splice(0,1,'a'));
alert(arr); // return :a,B,C,D
alert(arr.splice(0,2,'a or b'));// use a or b Replace a and B, return a,B
alert(arr); // return :a or b,C,D
var arr = ['A','B','C','D'];
//4 Parameters , The second parameter is 0, Add functions : The subscript for 1 Add aaa,bbb, no return value
alert(arr.splice(1,0,'aaa','bbb'));
alert(arr);// return :A,aaa,bbb,B,C,D
var arr = [1,2,2,2,4,2];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++){
if(arr[i] == arr[j]){
arr.splice(j,1);// Delete j The element at the location
j--;7
}
}
}
alert(arr);// return 1,2,4 Three elements 1、for loop
1 2 3 4 5 6 7 |
|
for Cycle is Js One of the most commonly used loop tools in , It is often used for array loop traversal .
2、for in loop (VUE Used in )
1 2 3 4 5 6 |
|
for in Loop is mainly used to traverse ordinary objects ,i Representing the object key value ,obj[i] For the corresponding value, When you use it to traverse an array , The same effect can be achieved in most cases , But don't do that , It's risky , because i The output is in string form , Instead of the numeric subscript required by the array , This means that in some cases , String operation will occur , Causing data errors , such as :'52'+1 = '521' Not what we need 53.
in addition for in In the cycle , Not only traverse its own properties , And you'll find prototype Up , So it's better to add a judgment to the circulation , Just use obj[i].hasOwnProperty(i), This avoids traversing too many unnecessary properties .
3、while loop
Same traversal cars Array , First use for Cycle method
1 2 3 4 5 6 7 8 9 10 11 |
|
And then there was while Cycle method
1 2 3 4 5 6 7 |
|
We found that , They can achieve the same effect , In fact, their underlying processing is the same , however for Loops can define 、 conditional 、 The auto increase and auto decrease operation is executed in a condition , The code looks more convenient , That's it .
4、do while loop
1 2 3 4 5 6 7 8 9 |
|
do while Cycle is while A variant of the loop , It first performs an operation , Then make conditional judgment , yes true Then continue the operation , yes false End of the cycle .
5、 Array forEach loop (VUE Used in )
1 2 3 4 5 6 7 |
|
forEach loop , Loop through each element in the array and take action , no return value , You don't need to know the array length , He has three parameters , Only the first one is required , Represents... Under the current subscript value.
Please also note ,forEach A loop cannot stop until all elements are called , It has no break sentence , If you have to stop , You can try try catch sentence , It's when it comes to forced exit , Throw a error to catch Catch , And then in catch Inside return, This will stop the cycle , If you use this method often , It's best to customize one of these forEach The function is in your library .
6、 Array map() fl Method (VUE Used in )
arr.map(function(i,[index],[arr]){ // i Represents each item in the array must index Represents the subscript of the element in the array Optional arr Represents the array object to which the current element belongs Optional
..........
})
1 2 3 4 5 6 |
|
map() Method returns a new array , The element in the array is the value after the original array element calls the function .
Be careful :map and forEach Methods can only be used to traverse arrays , It can't be used to traverse ordinary objects .
7、for of loop
1 2 3 4 5 6 |
|
边栏推荐
- HCIA静态路由综合实验
- C语言——关系运算符和逻辑运算符、if语句、switch语句、分支结构的嵌套
- (题意+详细思路+加注释代码) Codeforces Round #805 (Div. 3)F. Equate Multisets
- Lesson 5 - key control LED
- C language - assignment operator, compound assignment operator, self increasing and self decreasing operator, comma operator, conditional operator, goto statement, comment
- 【C语言】strlen与sizeof相关区分
- Lecture 4 - explain GPIO_ Write function and related routines
- 记录HandsomeBlog的star用户
- HCIP oSPF知识总结
- Static comprehensive experiment (comprehensive exercise of static route, loopback interface, default route, empty interface, floating static)
猜你喜欢

Simple application of rip V2 (V2 configuration, announcement, manual summary, ripv2 authentication, silent interface, accelerating convergence)

数字芯片的面积优化:第三届“华为杯”研究生创芯大赛数字方向上机题1详解

First acquaintance with C language (1)

Republishing and routing strategy of OSPF

HCIP 双向重发布以及路由策略

Timer interrupt experiment

C language -- nesting of relational and logical operators, if statements, switch statements, and branch structures

The basic configuration of static routing (planning of IP address and configuration of static routing) realizes the accessibility of the whole network.

Static comprehensive experiment (comprehensive exercise of static route, loopback interface, default route, empty interface, floating static)

【C语言】阶乘实现
随机推荐
CF 1333C Eugene and an array
数字集成电路:CMOS反相器(一)静态特性
Nb-iot networking communication
HCIA静态路由综合实验
Esp8266wi fi data communication
HCIA Basics (1)
Lvs+keepalived project practice
(题意+详细思路+加注释代码) Codeforces Round #805 (Div. 3)F. Equate Multisets
Wechat applet: user wechat login process (attached: flow chart + source code)
MGRE、PPP、HDLC综合实验
7.16 written examination of Duoyi network
C语言——关系运算符和逻辑运算符、if语句、switch语句、分支结构的嵌套
NPM reports an error, error: eperm: operation not permitted, MKDIR
Lecture 4 - explain GPIO_ Write function and related routines
Lora illumination sensor node data acquisition
STM32 introductory tutorial lesson 2
Lora communication application development
Codeforces Round #810 (Div. 2), problem: (B) Party
C language - assignment operator, compound assignment operator, self increasing and self decreasing operator, comma operator, conditional operator, goto statement, comment
Republishing and routing strategy of OSPF