search
HomeWeb Front-endJS TutorialAbout 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.

About array methods and loops in JavaScript

[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 tutorialweb 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!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.