search
HomeWeb Front-endFront-end Q&AWhat is the use of javascript arrays

What is the use of javascript arrays

Sep 14, 2022 pm 12:07 PM
javascript

In JavaScript, an array is a collection of ordered data, used to store large amounts of data. Multiple data can be stored at one time, and the length of the array can be dynamically adjusted; by using arrays, it can be Shorten and simplify program code to a large extent, thereby improving application efficiency.

What is the use of javascript arrays

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript Array is a collection of ordered data. Each member in the array is called an element, and the name (key) of each element is called the array index (Index). The length of the array is flexible and readable and writable; that is, the length of the array can be dynamically adjusted.

The role of arrays: Storing a large amount of data, multiple data can be stored at one time. By using arrays, program code can be shortened and simplified to a great extent, thereby increasing the efficiency of the application.

In JavaScript, you can use the Array object to define an array. In addition, the Array object also provides various properties and methods related to arrays.

Definition of array: Array Abbreviation: arr

Array is a data container in JS. It is one of the reference types.

Its function is very simple, it is used to hold multiple data, and The length of the array can be dynamically adjusted.


How to create array:

  • ##Literal

  • Constructor

Literal syntax:

var array name = [member 1, member 2, member 3, ...];

Array elements are separated by commas;

What is the use of javascript arrays

Constructor syntax:

var array name = new Array(member 1, member 2, member 3, ...) (at least there must be two or more array elements;) Small bug: when the parameterWhen there is only one parameter and the type of the parameter is a number, it will be regarded as the length of the array ;

var arr = new Arry(5 ); console.log(arr); The output result is:

var array name = new Array();

var arr = new Array ();//Create a new empty array

Note that Array 0, A must be capitalized


The array consists of two parts:

1: Index (also called subscript),

The subscript starts from 0;

2. Members (array elements):

Members have no restrictions and can be any type of data; It can be a string, it can be a number, it can be a Boolean value, it can be undefined, it can be null, it can also be an array;

What is the use of javascript arrays

##Get array elements:

The value of the array:

Array name [subscript]; The subscript starts from zero;

/ / Format: Array name [subscript] Subscript is also called index
/


/ Function: Get the value corresponding to the subscript of the array. If the subscript does not exist, undefined is returned. var arr = ['red',, 'green', 'blue'];

console.log(

arr[0]
); // red console.log(arr[2]
) ; // blue aconsole.log(arr[3]
); // The maximum subscript of this array is 2. There is no such array element, so the output result is undefined ;

Add members/modify members through index:

// 构造函数定义一个数组
var arr = new Array('张三', '李四', '王五', '赵六')

// 添加成员
arr[4] = '龚七'
console.log(arr)  //张三', '李四', '王五', '赵六','龚七'
// 修改成员
arr[0] = '王老五'
console.log(arr)  //'王老五', '李四', '王五', '赵六'
Special case: Setting multiple members through index will cause interruption in the middle On, empty; prohibited!

var arr = ["a", "b"];

arr[5] = "good";

console.log (arr); //


 遍历数组:

 What is the use of javascript arrays

What is the use of javascript arrays


 数组的属性length,就是数组成员的个数;

数组名.length

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

length表示数组的长度 它会跟着数组实时发生变化(动态监测数组元素的个数)

 console.log(arr.length)   //数组成员的个数: 8

 length属性可读可写  它也会影响数组的成员个数 但是我们一般不会主动修改该属性;

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

arr.length = 3;

console.log(arr.length);    

console.log(arr);

What is the use of javascript arrays

What is the use of javascript arrays

What is the use of javascript arrays


数组元素求和,求平均值:

What is the use of javascript arrays

求数组元素的最大值:

What is the use of javascript arrays

数组元素转字符串,并分割开:    推荐: 数组名.join("连接符")

What is the use of javascript arrays

求数组中大于10的成员,并挑选出来:

1What is the use of javascript arrays

1What is the use of javascript arrays

数组元素的倒叙:

1What is the use of javascript arrays


数组元素的增删改查;

unshift   头增       数组名.unshift("value")

作用:头部增加 (可以增加多个)

参数:添加的成员,可以是多个;

返回值:数组的新长度

var arr = ['张三', '李四', '王五', '赵六'];
var result = arr.unshift('王二',刘一)
console.log(result); // 6
console.log(arr); 
// ["王二", "刘一","张三", "李四", "王五", "赵六"]

push   尾增   数组名.push("value")

作用:尾部增加 (可以增加多个)

参数:添加的成员,可以是多个;

返回值:数组的新长度

var arr = ['张三', '李四', '王五', '赵六'];
var result = arr.push('王二',"刘一")
console.log(result); // 6
console.log(arr); // ["张三", "李四", "王五", "赵六", "王二","刘一"]

shift   头删    数组名.shift()   只删除第一个,()括号内为空;

作用:删除数组的头部第一项

参数:无;

返回值:被删除的那一项

var arr = ['张三', '李四', '王五', '赵六'];
var result = arr.shift()
console.log(result); // 张三
console.log(arr) //  ['李四', '王五', '赵六'];

 pop   尾删    数组名.pop()   只删除最后一个,()括号内为空;

作用:删除数组最后一项;

参数:无;

返回值:被删除的那一项

var arr = ['张三', '李四', '王五', '赵六'];
var result = arr.pop();
console.log(result); // 赵六
console.log(arr) //["张三", "李四", "王五"]

concat      拼接,合并;   数组名.concat("value")

作用:合并

参数:任意个、任意类型

返回值:一个新的合并后的数组

特点:没有改变原来的数组

var arr1 = [1, 2, 3];

var arr2 = [4, 5, 6];

var newArr = arr1.concat(arr2, "good", true, 1);

console.log(arr1); // 1,2,3

console.log(arr2); //4,5,6

console.log(newArr); //1, 2, 3, 4, 5, 6, "good", true, 1

slice  截取     数组名.slice(start,end)   参数是下标; 包括开头,不包括结尾;

slice的本质是复制(浅复制) 

作用:截取

参数:

  1. 没有参数 截取全部

  2. 一个参数 从指定位置截取到最后(包括最后)

  3. 两个参数 从指定开始位置截取到指定的结束位置 1. 这两个参数都是下标 2. 开始位置(包含) 3. 结束位置(不包含) 4. 第二个参数要比第一个大;

  4. 参数可以是负数,负数是从后面开始,最后一个是-1;

特点:不改变原数组

没有参数 (截取全部的)
var arr = ['张三', '李四', '王五', '赵六'];
var arr1 = arr.slice();
console.log(arr1)  //  ["张三", "李四", "王五", "赵六"]

一个参数 (从指定位置截取到最后(包括最后))
var arr = ['张三', '李四', '王五', '赵六'];
var arr2 = arr.slice(1);
console.log(arr2) // ["李四", "王五", "赵六"]

两个参数 (包括开始,不包括结尾)
var arr = ['张三', '李四', '王五', '赵六'];
var arr3 = arr.slice(1, 3);
console.log(arr3) // ["李四", "王五"]

参数为负数; (还是第二个参数要比第一个大)

var arr = ['张三', '李四', '王五', '赵六','刘一'];
var arr3 = arr.slice(-3, -1);
console.log(arr3) // ["王五","赵六"]

PS: 如果参数是负数 那么表示从后往前数 最后一个值是-1

 splice    操作数组     数组名.splice(参数1,参数2,参数3)

作用:用于操作数组成员

参数:

  • 参数1:操作开始位置; (从第几个索引号后开始, 可以看成直接从顺序的第几个后开始的)
  • 参数2:删除的成员个数; (为0,是添加)
  • 参数3:从第三个参数开始是添加的成员;

返回值:被删除的那些成员组成的数组

特点:会改变原数组

// 删除

var arr = ['张三', '李四', '王五', '赵六'];
var result = arr.splice(1, 2)
console.log(result); // ["李四", "王五"]
console.log(arr); // ["张三", "赵六"]   
----------------------------------------------------------------------
// 插入   第二个参数为0;

var arr = ['张三', '李四', '王五', '赵六'];
var  result = arr.splice(2, 0, '小绵羊');
console.log(result); // []
console.log(arr) // ["张三", "李四", "小绵羊", "王五", "赵六"]
------------------------------------------------------------------------
// 替换   第一个参数从哪里开始, 第二个参数删除几个,第三个参数...添加的新成员;

var arr =['张三', '李四', '王五', '赵六'];
var result = arr.splice(2, 1, '小绵羊', '大绵羊');
console.log(result); // ["王五"]
console.log(arr) // ["张三", "李四", "小绵羊", "大绵羊","赵六"]

-----------------------------------------------------------------------------------------------

如果只有一个参数 则第二个参数默认为删除所有;

var arr = ['张三', '李四', '王五', '赵六'];

var result = arr.splice(2);

console.log(result);  // ["王五","赵六"]

console.log(arr) // ["张三", "李四"]

indexOf      数组名.indexOf("数组元素")

作用: 查找

参数:被查找的成员;

返回值:下标(索引);      若有该成员返回该索引; 若没有就返回-1

 var arr = ["a", "b", "c", "d", "e", "f"];

var idx = arr.indexOf("d"); //3

var idx = arr.indexOf("aa"); //-1

console.log(idx);

 join    数组名.join("连接符")

作用:转字符串

返回值:数组元素变成字符串类型,链接符相连;

参数: 拼接符号(可选)

数组名.join()  不写内容,默认是逗号,  ;

数组名.join(''), '' 没有空格隔开, 数组直接相连;

数组名.join('   ')  空格隔开, 空格

数组名.join('*')

var arr =['张三', '李四', '王五', '赵六'];
var str = arr.join();
console.log(str); // 张三,李四,王五,赵六

var str1 = arr.join('+');
console.log(str1); // 张三+李四+王五+赵六 

var str2 = arr.join('❤');
console.log(str2); // 张三❤李四❤王五❤赵六

//返回值是数组元素变成字符串,并连接符相连;

 reverse  数组倒叙     数组名.reverse()   括号内不跟参数;

作用:将数组的成员倒序

返回值:倒叙的原数组

参数:无

特点:会改变原数组

var arr =['张三', '李四', '王五', '赵六'];
console.log(arr) // ["张三", "李四", "王五", "赵六"]

var arr1 = arr.reverse();
console.log(arr1) // ["赵六", "王五", "李四", "张三"]
console.log(arr === arr1) // true

console.log(arr)  // ["赵六", "王五", "李四", "张三"]     //会改变原数组;

其他方法:

1What is the use of javascript arrays

sort      排序         数组名.sort(函数)  升序或降序

作用:将数组成员按照指定规则排序

返回值:排序后原数组

参数:规则函数; 不跟参数(//不跟参数,会先转为字符串,然后按照ascii码排序首字母排;)

特点:会改变原数组

var arr = [89, 96, 45, 66, 78, 3, 100, 1];

arr.sort(function(a, b) {

return a - b;     // 升序

        });

 console.log(arr);  //   [1, 3, 45, 66, 78, 89, 96, 100];

-------------------------------------------------------------------------

var arr = [89, 96, 45, 66, 78, 3, 100, 1];

arr.sort(function(a, b) {

return b - a;     // 降序

        });

 console.log(arr);  //   [100, 96, 89, 78, 66, 45, 3, 1];

--------------------------------------------------------------

var arr = [89, 96, 45, 66, 78, 3, 100, 1];

arr.sort();                //不跟参数,会先转为字符串,然后按照ascii码排序首字母排;

console.log(arr);    //[1, 100, 3, 45, 66, 78, 89, 96]

交换两个变量的值

var a = 4;
var b = 5;

// 交换两个变量的值要借助第三个变量
var c = b;
b = a;
a = c;

console.log(a); // 5
console.log(b); // 4

 数组的冒泡排序

for (var j = 0; j
  for (var i = 0; i
    if (arr[i] > arr[i + 1]) {
      var temp = arr[i];
      arr[i] = arr[i + 1];
      arr[i + 1] = temp;
    }
  }
}

----------------------------------------------------------

要排序 就要比较大小  

First compare the first number with the second number. If the first number is larger, swap positions. After the comparison, the number in the second position of the array must be larger than the first one.

Then take the first number After comparing the second and third numbers, the third number in the array must be larger than the number in the second position.

And so on, after one round of comparison, the final number must be the largest

The second round continues the comparison from the beginning. After the second round, the second largest number can be determined

The third round...

to the end.

// // The outer loop determines the execution of the inner loop Number of times

for (var j = 0; j

                                                                                      

                                                 (var i = 0; i

// Determine if the front is larger and the back is smaller, then exchange

if (arr[i ] > arr[i 1]) {

var temp = arr[i];

arr[i] = arr[i 1];

arr[i 1]=temp;

##Two-dimensional array

Each member of an array is also an array, which is called a two-dimensional array.

One-dimensional array: [1, 2, 3, 4, 5, 6]

Two-dimensional array:

[

[1, 2 , 3, 4, 5, 6],

[1, 2, 3, 4, 5, 6],

[1, 2, 3, 4, 5, 6]

...

]

Method to clear the array:

// Method 1 recommendedarr = [ ];


// Method 2arr.length = 0;
// Method 3
arr.splice(0, arr.length);
[Recommended learning:
javascript advanced tutorial
]

The above is the detailed content of What is the use of javascript arrays. For more information, please follow other related articles on the PHP Chinese website!

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
React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode PurposeReact Strict Mode PurposeApr 02, 2025 pm 05:51 PM

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)