当前位置:网站首页>Js----- Chapter 4 array
Js----- Chapter 4 array
2022-07-24 23:16:00 【Monkey hanging on a tree】
review
loop :
while
Count variables
while( Conditions ){
// The loop body
Count variable update
}
do..while
for
for( Count variables ; Conditions ; Count variable update ){
The loop body
}
- Feynman method of learning
break: encounter break The loop ends
continue: encounter continue, Then the following code will not be executed , Go straight to the next cycle
break and continue: You can talk to while,do..while,for Use a combination of
- break and switch Use a combination of
Supplementary cases :
// Loop input 5 Personal scores , If the score is correct, the total score will be output , average
// If a score entered is incorrect ( Less than 0 Or greater than 100), Then directly terminate the loop , And output an error prompt , in addition , Cannot output total score and average score .
// Loop input 5 Personal scores , If the score is correct, the total score will be output , average
// If a score entered is incorrect ( Less than 0 Or greater than 100), Then directly terminate the loop , And output an error prompt ,
// in addition , Cannot output total score and average score .
// Define the summation variable
var sum = 0;
// Define tag variables , Used to record error conditions
var flag = false;
// Loop input
for(var i=1;i<=5;i++){
// Enter the score
var score = Number(prompt(" Please enter the first "+i+" A student's score ",""));
// If the score is wrong , Then the prompt is wrong , Modify tags , End of cycle
if(score<0 || score>100){
document.write(" Something went wrong ");
flag = true; // Modify tags
break; // End of cycle
}
// Add up the scores
sum += score;
}
if(flag==false){
// Output total score average score
document.write(" Total score :"+sum+" average :"+sum/5);
}The objectives of this chapter
To define an array
Access assignment of array
Array insertion , Delete , Traverse
Array method
1. Array
1.1 What is an array ( An array is a set of numbers )
Array (Array) yes Orderly The sequence of elements . [1] If a finite number of variables aggregate name , So the name is array name . The variables that make up an array are called the components of the array , Also known as an array of elements , Sometimes it's also called Subscript variable . The number used to distinguish the elements of an array is called the subscript . The array is in Programming in , For convenience , A form of organizing several elements in an orderly form . [1] The collection of these ordered data elements is called an array . An array is a collection of data of the same type .
An array is an ordered sequence of elements :
Each element in the array has its own number Number from 0 Start , To the length of the array minus 1 until , Called subscript .
How to access the data in the array :
Access by subscript , Is to distinguish each data in the array .

1.2 Why use arrays
For storing a large amount of data , Arrays can easily open up space in batches , Store batch data , There is no need to define variables one by one .
1.3 General use of arrays
Definition of array
// Mode one : Create an empty array , No space length var Array name = new Array(); // Mode two : Create an array with a specified length space var Array name = new Array( Length number ); // Mode three : Create an array with some initial values var Array name = new Array( data 1, data 2, data 3); // Mode 4 : Use literal quantity "[]", Create an empty array .** Commonly used ** var Array name = []; // Methods five : Use literal quantity "[]", Create an array with initial values ** Commonly used ** var Array name = [ data 1, data 2, data 3...];
Value and assignment of array
Array value : Array name [ Subscript ];
Array assignment ( modify ): Array name [ Subscript ] = Value to modify ;
<script type="text/javascript">
// Common variables : Store one data at a time
// Array : Batch data can be stored
// scene : Store a class 60 One of the js fraction
/*var score1 = 78;
var score2 = 89;
var score3 = 98;
....
var score60 = 76;*/
// How to create an array
// The way 1: var Array name = new Array( length ); // The length can be omitted
// The way 2: var Array name = new Array( data 1, data 2, data 3);// Create data with initial values
// The way 3: var Array name = []; // Create an empty array literally
// The way 1:var Array name = new Array( length )
// Create an empty array
//var ary1 = new Array();
// Create a length of 5 The array space of
var ary = new Array(5);
//length: The length of the output array
document.write(" length :"+ary.length+"<br/>");
// The assignment of an array : Array name [ Subscript ] = data
ary[0] = 98;
ary[1] = 33;
ary[4] = 56;
// Access the contents of the array
document.write(ary[0]+"<br/>");
document.write(ary[1]+"<br/>");
document.write(ary[2]+"<br/>");
document.write(ary[3]+"<br/>");
document.write(ary[4]+"<br/>");
document.write("<hr/>");
document.write(ary[5]); // Array subscript exceeded , No mistake. , Output undefined
document.write("<hr/>");
// Use a loop to output the contents of the array
//ary.length yes 5:i The change of : 0 1 2 3 4
for(var i=0;i<ary.length;i++){
document.write(ary[i]+"<br/>");
}
</script>
<script type="text/javascript">
// var ary = new Array(); // The length is 0 Array of
// var ary = new Array(10); // There's only one whole number ,
// Indicates that the array length is 10, At this time, the contents of the array are undefined
/*
// Create a length of 4 Array of , The initial data of the array are 10,11,12,13
var ary = new Array(10,11,12,13);
// length
document.write(" length :"+ary.length+"<br/>");
document.write(ary[0]+"<br/>");
document.write(ary[1]+"<br/>");
document.write(ary[2]+"<br/>");
document.write(ary[3]+"<br/>");
*/
/*
// Use literals to define empty arrays
var ary = [];
document.write(" length :"+ary.length+"<br/>");
//js The array of can be dynamically expanded
ary[0] = 10;
ary[1] = 20;
ary[2] = 30;
document.write(" length :"+ary.length+"<br/>");
*/
// new Date(): Get system time
// The data in the array can store any type
var ary = ["abc",100,2.234,new Date()];
document.write(" length :"+ary.length+"<br/>");
for(var i=0;i<ary.length;i++){
// Use Array name [ Subscript ] Access each array element
document.write(ary[i]+"<br/>")
}
document.write("<hr/>");
// Use for each Output array elements
// among i Is the subscript of an array
for(var i in ary){
alert(i+" : "+ary[i]);
}
</script>Array traversal
Using normal for Loop traversal key exercises
var ary = ["abc",100,2.234,new Date()];
document.write(" length :"+ary.length+"<br/>");
for(var i=0;i<ary.length;i++){
// Use Array name [ Subscript ] Access each array element
document.write(ary[i]+"<br/>")
}Use forEach Traverse
var ary = ["abc",100,2.234,new Date()];
document.write(" length :"+ary.length+"<br/>");
// Use for each Output array elements
// among i Is the subscript of an array
for(var i in ary){
alert(i+" : "+ary[i]);
}1.4 Array operation
Array search ( Focus on practice )
1. Please enter 5 Results of students , And stored in the array
2. Traversing the array to find the score is 80 Points of , How many students

<script type="text/javascript">
// Define array storage 5 Results of students
// And find the first 80 Where is the score in the array
// Enter grades :89,56,78,80,98
// 0 1 2 3 4
// 76,80,88,87,32
// 0 1 2 3 4
// Define the length as 5 Array of
var aryScore = new Array(5);
// Loop input 5 A student's score
for(var i=0;i<aryScore.length;i++){
// Enter your grades
var score = Number(prompt(" Please enter the first "+(i+1)+" A student's score :",""));
// Store scores in an array
aryScore[i] = score;
}
// Print the array directly
//document.write(aryScore);
// Loop through groups , And determine whether each array element is 80 branch , yes 80 The sub rule displays the corresponding array subscript
for(var i=0;i<aryScore.length;i++){
//alert(aryScore[i]);
// Traversal array , Judge whether the data currently traversed is 80
if(aryScore[i]==80){
alert("80 The subscript of the score is :"+i);
break;
}
}
</script>Array insertion
An array is known : var ary = [20,12,33,45,67];
Now enter an arbitrary data , Insert the index into the array as 2 Location

<script type="text/javascript">
// Known array :20,12,33,45,67
// The subscript for 2 Insert a data at the position of ( Enter your own )
var ary = [20,12,33,45,67];
document.write(ary+"<br/>")
var num = Number(prompt(" Please enter a data to insert :",""));
// Use a loop to shift
for(var i=ary.length;i>2;i--){
// Shift the front data in the array to the back
ary[i] = ary[i-1];
}
// Store the data to be inserted in the subscript 2 On the array space of
ary[2] = num;
document.write(ary);
</script>Array deletion

Bubble sort
Sort :
- What is sequencing : From bottom to top , Present in a specific order from high to low
- Why order : You can get specific data directly by sorting , Improve the utilization efficiency of data
The core of sorting : Comparison and transposition

<script type="text/javascript">
// Bubble sort
// Data comparison transposition
var ary = [56,32,8,76,12,1,3,6,4,5,100,99];
// 0 1 2 3 4
document.write(ary+"<br/><hr/>"); //56,32,8,76,12
// N Bubble order of meta array , Small forward movement compared with two
// The outer layer circulates from 1 beginning , Inner circulation decreases i Go to
// Bubble sort
for(var i=1;i<ary.length;i++){
// Achieved the first round of four comparisons
for(var j=0;j<ary.length-i;j++){
// Comparison and transposition
if(ary[j]>ary[j+1]){
var temp = ary[j];
ary[j] = ary[j+1];
ary[j+1]=temp;
}
}
}
document.write(ary+"<br/><hr/>"); //
</script>1.5 A common method for arrays / function
name | describe |
join( Separator ) | Convert an array to a string concatenated with a specific delimiter |
concat(arr1,arr2) | Merge with another array into a new array |
reverse() | Invert array |
sort() | Sort the array |
push(ele1,ele2) | Add a new element to the end of the array |
unshift(ele1,ele2) | Add a new element to the beginning of the array |
pop() | Delete the last value in the array Return the deleted value |
shift() | Delete the first value in the array Return the deleted value And pop() contrary |
splice( Location , Delete the number , The new data ..) | Delete 、 Replace 、 Insert array elements |
indexOf(ele) | Find the subscript position of the element |
//var ary = [20,10,30,50,60];
//document.write(ary+"<br/>");
// Put the elements in the array , Concatenate the string with the specified symbol
//var res = ary.join("----");
//document.write(res);
// Invert the array
//ary.reverse();
//document.write(ary);
//var ary2 = [];
// Adding elements to an array , Add from the end of the array
//ary2.push(100);
//ary2.push("abc");
//ary2.push(2.34);
//document.write(ary2+"<br/>");
// Delete the value at the end of the array
//ary2.pop();
//document.write(ary2);
//var ary3 = ["aaa","bbb","ccc","ddd","eee"];
//document.write(ary3+"<br/>")
// Use splice Delete the subscript as 2 The elements of
// From the subscript 2 The location of , Delete an element
//ary3.splice(2,1);
//document.write(ary3);
// From the subscript 2 The location of , Don't delete elements , But add two new elements
//ary3.splice(2,0,"xxx","yyy");
//document.write(ary3);
// Find the position of an element in the array
// If we can't find a way back -1
//alert(ary3.indexOf("ggg"));
var ary4 = [5,3,2,1,4,12,100];
document.write(ary4+"<br/>");
// Sort array elements : Compare the string in character order
ary4.sort();
document.write(ary4);summary
Definition of array
Assignment and use of arrays
Array operation : Traversal search , Insert , Delete
Common methods of data
example :
Use splice Realize the data insertion of ordered array .
Enter a number through the input box , After inserting the input number into the array, make sure that the array is still in order :
Example : Array [10,50,70,89,99], Enter a number 83, take 83 Insert into the array , After insertion, the array is still in order
The array becomes [10,50,70,83,89,99]
... Given an ordered array ary
// Defining variables , In the record array , The first location larger than the data to be inserted
var pos = -1;
for(var i=0;i<ary.length;i++)
{
// Compare the data in the array and the data to be inserted next to each other
if(ary[i]>num)
{
// When the first data larger than the inserted data is found , Where to record this data , And exit the loop
pos = i;
break;
}
}
alert(pos);
// After the cycle , Find the location to insert
// Use splice function , Data to be inserted , Insert in the specified location
ary.splice(pos,0,num);
// Output the inserted result
document.write(ary);边栏推荐
- Okaleido tiger NFT即将登录Binance NFT平台,后市持续看好
- 给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享
- 痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异
- salesforce零基础学习(一百一十六)workflow -&gt; flow浅谈
- Power consumption of chip
- 凸优化基础知识
- Convert a string to an integer and don't double it
- Time series data in industrial Internet of things
- Go basic notes_ 4_ map
- RichTextBox operation
猜你喜欢

Error connecting MySQL database with kettle
![[1184. Distance between bus stops]](/img/dd/3437e6a14ac02dac01c78b372a5498.png)
[1184. Distance between bus stops]

Understanding complexity and simple sorting operation

JUC concurrent programming - Advanced 05 - lock free of shared model (CAS | atomic integer | atomic reference | atomic array | field updater | atomic accumulator | unsafe class)

一文读懂Elephant Swap的LaaS方案的优势之处

Notes of Teacher Li Hongyi's 2020 in-depth learning series 3

VGA display based on FPGA

把字符串转换成整数与不要二

Alibaba cloud SSL certificate

基于FPGA的VGA显示
随机推荐
Process / thread synchronization mechanism
Salesforce zero foundation learning (116) workflow - & gt; On flow
The rule created by outlook mail is invalid. Possible reasons
必会面试题:1.浅拷贝和深拷贝_浅拷贝
The size of STM32 stack
MySQL查询慢的一些分析
Use and partial explanation of QDIR class
QT6 with vs Code: compiling source code and basic configuration
聊聊 Redis 是如何进行请求处理
"Yuan universe 2086" outsold "San ti" in one-day sales and won the champion of JD books' one-day science fiction list
Introduction to HLS programming
价值驱动为商业BP转型提供核心动力——业务场景下的BP实现-商业BP分享
Notes of Teacher Li Hongyi's 2020 in-depth learning series 3
Mandatory interview questions: 1. shallow copy and deep copy_ Deep copy
Connector in C
Old Du servlet JSP
Alibaba cloud SSL certificate
Is it safe to log in the securities account on the flush
QT | event system qevent
How static code analysis works