Home Web Front-end JS Tutorial Arrays for Getting Started with JavaScript [Must-read for Beginners]

Arrays for Getting Started with JavaScript [Must-read for Beginners]

Dec 06, 2016 am 10:32 AM
javascript

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles