About array methods and loops in JavaScript
This article brings you relevant knowledge about javascript, which mainly introduces array methods and loops in JavaScript. It has a good reference value and I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
1. Basic concepts
JavaScript arrays are used to store multiple values in a single variable. It is a collection of one or more values with the same data type
2. Three ways to create an array
(1) Use the JavaScript keyword new to create an Array object and assign values separately
//1、创建数组 new 一个Array() 对象 let arr = new Array(); arr[0] = "html"; arr[1] = "css"; arr[2] = "javascript"; arr[3] = "java";
(2) Assign a value at declaration time
//2、创建数组 在Array()对象里面直接赋值 let arr1 = new Array("html","css","java","javaweb","javascript");
(3) Use array literals to create directly
//3、通过[]直接创建 let arr2 = ["html","css","java","javascript","javaweb"];
For the sake of simplicity, readability and execution speed , please use the third method (array text method).
3. Access the array
(1) Reference an array element by referencing the index number (subscript number) , [0] is the element in the array The first element. [1] is the second one. Array index starts from 0;
document.write(arr1[0]);
(2) The complete array can be accessed by referencing array name
console.log(arr1);
(3) Modify the array elements.
arr[1] = "css";
4. Common properties of arrays
The length property returns the length of the array (the number of array elements).
console.log(arr,arr.length);//控制台输出数组和数组长度
5. Common methods for arrays
(1) join(): Put all the elements of the array into a string and separate them by a separator;
//1、join()方法 以分隔符将数组分隔转化为string let arr = new Array("html","css","javascript","java","web","mysql"); console.log(arr,typeof(arr)); let newarr = arr.join("+"); console.log(newarr,typeof(newarr));
(2) split() method converts the string into array array type through delimiter
// 2、split()方法 将字符串通过分隔符转化为array数组类型 // split() 函数验证邮箱格式 let email = prompt("请输入你的邮箱:"); console.log(email); let arr1 = email.split("@"); console.log(arr1,typeof(arr1)); document.write("你的账号为:"+arr1[0]+"<br>"+"你的网站时:"+arr1[1]);
Use the above two methods to eliminate all spaces between strings
//功能 剔除字符串里的所有空格 function trimAll(str){ let nowstr = str.trim();//先剔除两端的空格 let arr = nowstr.split(" ");//split() 转换为数组 用空格分隔 for(let i = 0;i<arr.length;i++){//循环遍历 if(arr[i] == ""){ arr.splice(i,1);//遇到空格删除 i--; } } return arr.join("");//join() 转化为字符串 } let nowstr = trimAll(" 1 2 4 5 "); console.log(nowstr);
(3) sort(): Sort the array
let arr = [31,23,26,76,45,1,90,6,24,56]; //sort() 函数 对数组进行排序 默认按数字首位进行排序 //添加参数 参数为匿名函数 arr.sort(function(a,b){ // return a-b; //正序排序 return b-a; //倒序排序 }); console.log(arr);
Note: The following method operates on the array itself
(4) push(): Add an element to the end of the array or more elements, and returns the new length;
(5) pop(): Delete the element at the end of the array;
(6) unshfit(): Add elements to the head of the array;
(7) shfit(): Delete the head element of the array;
(8) splice(): Universal array method: 1. Delete elements in the array; 2. Add elements; 3. Replace elements
let arr = ["html","java","csss","javascript"]; console.log("旧数组:"+arr); //对数组自身进行操作 arr.push("weeb");//在数组末尾添加元素 可以有多个参数 之间用逗号隔开 arr.pop();//删除末尾元素 没有参数 arr.unshift("react","mysql");//在数组头部添加元素 可以有多个参数 之间用逗号隔开 arr.shift();//删除数组头部的元素 没有参数 arr.shift();//删除需要多次删除 或者利用循环 arr.splice(0,2);//数组万能方法 删除任意位置元素 参数为: 起始下标,删除数目 arr.splice(3,2,"java","html");//添加元素 参数为:数组没有的下标,添加数目,添加的数据 arr.splice(1,1,"javaweb")//替换元素 参数为:起始下标,替换个数,替换数据 如果替换数据小于替换个数 则执行删除功能 console.log("新数组:"+arr);
6. Commonly used methods of looping through arrays
Loop: Loop is to repeatedly execute a certain function when the conditions are met. One operation
1. Use for loop to traverse the array. Known conditions and known length. Judge first and then loop.
let arr = new Array("html","css","javascript","java","web","mysql"); //1、利用for循环遍历数组 已知条件 已知长度 先判断后循环 for (let i = 0;i < arr.length;i++){ document.write(arr[i]+"<br>"); }
2. Use while loop to traverse the array. Unknown conditions and unknown length. Judge first and then loop.
//2、利用while循环遍历数组 未知条件 未知长度 先判断后循环 let i = 0; while(i < arr.length){ document.write(arr[i]+"<br>"); i++; }
3. do while loops through the array and executes it at least once
//3、至少执行一次 do while 循环遍历数组 let j = 0; do{ document.write(arr[j]+"<br>"); j++; } while(j < arr.length);
4. for of loops through the array value is directly the element value
//4、for of 循环遍历数组 value直接元素值 for(let value of arr){ document.write(value+"<br>"); }
5. for in loops through the object i is key Key is specially used to loop through objects, and can also loop through arrays
//5.for in 循环遍历对象 i 为 key键 专门用来循环遍历对象 for(let i in arr){ document.write(arr[i]+"<br>"); }
6. forEach() array method Anonymous callback function [Loop through arrays]
//6.forEach() 数组方法 匿名回调函数 【循环遍历数组】 arr.forEach(function(value,index,arr){ document.write(index+"---"+value+"----"+arr+"<br>"); })
7. Use map() array method Traversing the array has a return value
//7、利用map() 数组方法遍历数组 有返回值 // 返回一个新的数组 和老数组长度一定一致,有可能是二维数组 let newarr = arr.map(function(value,index,oldarr){ document.write(index+"---"+value+"----"+oldarr+"<br>"); if(index == 0){ value = "12345"; } return [value,index]; }); console.log(newarr);
8. Using the flatmap() array method to traverse the array has a return value and also returns a new array
//8、利用flatmap() 数组方法遍历数组 有返回值 同样返回一个新的数组 //长度有可能和原来数组不一致,但一定是一维数组 flat() 为降维函数 let newarr1 = arr.flatMap(function(value,index,oldarr){ document.write(index+"---"+value+"----"+oldarr+"<br>"); if(index == 0){ value="321"; } return [value,index]; }); console.log(newarr1);
[Related recommendations :javascript video tutorial、web front-end】
The above is the detailed content of About array methods and loops in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
