search
HomeWeb Front-endJS TutorialArrays for Getting Started with JavaScript [Must-read for Beginners]

1. Define the array.

  There are two ways to define an array:

  1. var arr1 = []; //Define an empty array

   2. var arr2 = [1,2,3,"str1","str2"]; // Define an array with 5 elements.

  3. var arr3 = new Array(3); //Define an empty array

  4. var arr4 = new Array(1,2,3,"str1","str2"); //Define an empty array with a specified length is an array of 5.

2. Reading and writing of array elements.

   arr[0]; //Read the first array element

  arr[0] = "str1"; //Change the value of the first element of the array.

3. Sparse array.

  A sparse array represents an array with non-consecutive indexes starting from 0. Usually the length of the array represents the number of elements in the element. If the array is sparse, the length attribute value will be greater than the number of elements.

  The in operator is used to detect whether an element exists at a certain position. Note that undefined is also considered to exist.

  For example: var a1 = [,,];

  var a2 = new Array(3);

   0 in a1; //true, because a[0] has undefined elements

  0 in a2; //false , a2 has no element at index 0

IV. Array length

  The length attribute is used to mark the length of the array

  For example: var arr = [1,2,3,4,5];

   arr.length; / /5 The arr array has 5 elements

5. Adding and deleting array elements

  push: //Add an element at the end of the array

var arr = [1,2,3];

  arr.push( 4,5); //arr becomes [1,2,3,4,5]

  delete: //Delete an element at a certain position in the array

  var arr = [1,2,3]

  delete arr [1]  //arr becomes [1,,3]

  1 in arr    //false

6. Array traversal

  Array traversal is usually implemented using the for statement

  var arr = [1,2, 3,4,5];

 for(var i = 0.i

 if(!a[i]) continue;    //Skip null, undefined and non-existent elements

   }

7. Multi-dimensional array

   A multi-dimensional array is an array of elements or an array

   For example: var arr = [[1,2,3],[,4,5,6]];

   arr[1 ][1]; // 5

8. Array methods

  1. join() Used to convert all elements in the array into strings and connect them together. You can also customize the connection characters

  var arr = [ 1,2,3];

   arr.join();   // => "1,2,3"

    arr.join("=="); // => "1==2= =3";

   2. reverse() Used to reverse the order of array elements

   var arr = [1,2,3];

   arr.reverse(); // The arr array becomes [3,2 ,1]

  3. sort(); // Used to sort the elements in the array. A function can be passed in for sorting. If it is empty, it will be sorted alphabetically. The undefined elements are sorted to the end

  var arr = [1,2,3];

  a.sort(function(a,b){

   return a-b; //Sort standard negative number 0 positive number, the comparison result returns the small one first The one

   }); //The value of the arr array is [1,2,3] If the second condition becomes b-a, the result is [3,2,1]

   4. concat() //Used for Combine a new array and return a new array

  var arr = [1,2,3]

   arrnew = arr.concat(4,5) //The arrnew array is [1,2,3,4,5 | / Used to return an array composed of elements in the specified range of the array. If a parameter is entered, it is the array from this parameter to the end. The two parameters are, the first parameter is the starting position, and the second parameter is the number.

    var arr = [1,2,3,4,5];

   var arr1 = arr.slice(2); //[3,4,5]

   var arr2 = arr.slice(1,3 ); //[2,3]

   6. splice()   Delete or add elements. It will change the original array itself, which is equivalent to the reference (ref) in C#. The original array is an array composed of deleted elements, and the return value is an array composed of remaining elements.

   var arr = [1,2,3,4,5];

  var arr1 = arr.splice(1,3); //arr is [2,3,4], and the returned array arr1 is [1 ,5]

  var arr2 = [1,2,3,4,5];

  var arr3 = arr2.splice(2,0,'a','b'); //Delete starting from the 2nd position , delete two elements, and then insert 'a', 'b' from that position; arr2 is [] because no elements are deleted, arr3[1,2,'a','b',3,4,5]

   7. push() and pop() Add or delete an element at the end of the array. When adding, it returns the last element added. When deleting, it returns the last element added. The return value is the deleted element.

   The push() function adds an element to the end of the array.

   pop()  Function deletes the last element of the array.

   var arr = [1,2,3]

    arr.push(4); pop(); //arr1 is [1,2]

   8. unshift() and shift()

   shift(), unshift() and push(), pop() are just operations on the head of the array rather than the tail.

   shift() Removes an element from the head of the array, and the return value is the deleted element.

   unshift() Adds an element to the head of the array and returns the last element added.

   var arr = [1,2,3];

   var a = arr.shift(); //arr becomes [2,3] a is 1

  var arr1 = [1,2,3];

   var b = arr1.unshift([4,5]); //arr1 becomes [4,51,2,3], b is 4 Return to the last one added, add 5 first and then add 4

  9. toString() and toLocaleString() Convert the array into a string

   var arr = [1,2,3]

   arr.toString(); // Generate "1,2,3" and join without using any parameters ()it's the same.

2. Array methods in ECMAScript

  1. forEach() forEach() traverses the array from beginning to end and calls the specified function for each element.

var arr = [1, 2, 3, 4, 5];

var sum = 0;

arr.forEach(function (value) {

sum + value;

});
document.write(sum ); //sum ends up being 15

   2. map() The map() method passes each element of the called array to the specified function and returns an array.

var arr = [1, 2, 3, 4, 5];

var arr1 = arr.map(function (value) {

return value + 1;

});

document.write(arr1.join() ); //arr1 is [2,3,4,5,6]

   3. filter() Filter() filters. The returned elements are a subset of the calling array, filtering out elements that do not meet the conditions.

var arr = [1, 2, 3, 4, 5, 6];

var arr1 = arr.filter(function (i) { return i % 2 == 0 });

document.write(arr1.join ()); //arr1 is [2,4,6]

4. every() and some()

Every() returns true if and only if all elements in the array call the judgment function and return true true. Stop traversing when false is returned for the first time.

   some() returns true when there is an element in the array and the judgment function is called to return true. Stop traversing when true is returned for the first time.

var arr = [1, 2, 3, 4, 5, 6];

var a = arr.every(function (x) { return x > 3; }); var b = arr.some(function (y){ return y > 3; });

           document.write("The value of a is: " + a); // The value of a is false, not all elements in a are greater than 3

         document.write(" The value of b is: " + b); //The value of b is true, and there are elements in b greater than 3


   5. reduce() and reduceRight()

   reduce()  Combine the elements in the array with the specified function , generates a single value, the first parameter is the simplified operation function, and the second parameter is the initial value passed to the function. The final result is the initial value and is calculated again based on the combined function and the final result. The second parameter, the initial value, can be omitted. When the initial value is omitted, calculation starts directly from the first element.

var arr = [1, 2, 3, 4, 5, 6];

var count = arr.reduce(function (x, y) { return x + y; },0);

document.write(count );

   reduceRight(); The only difference from reduce() is that it selects elements from right to left for calculation.

   6. indexOf() and lastInsexOf()

   indexOf()  indexOf() returns the index of the first element found from the beginning to the end.

   lastIndexOf() lastIndexOf() searches for elements in reverse order and returns the index of the first found element.

var arr = [1, 2, 3, 2, 1];
var i = arr.indexOf(2); //Search from beginning to end, the first time 2 is encountered is arr[1], so 1 is returned
var j = arr.lastIndexOf(2); //Search from the end to the beginning. The first time 2 is encountered is arr[3], so 3 is returned. document.write(i + "
");
document .write(j);

 7. Array.isArray(); //Determine whether an object is an array object

var arr = [1, 2, 3];

var str = "str1";
document.write( Array.isArray(arr)); //return true arr is an array object
        document.write(Array.isArray(str)); //return false str is a string, not an array object


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.

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

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)