Home  >  Article  >  Web Front-end  >  How to modify an element in an array in ES6

How to modify an element in an array in ES6

青灯夜游
青灯夜游Original
2022-04-15 17:53:534702browse

Modification method: 1. Use the "array name [specified subscript value] = new value;" syntax, access the specified element through the subscript, and reassign the value to the element for modification; 2. Use "array .splice(start article, delete number of elements, insert value 1, insert value 2)" statement, delete n elements from the specified position and insert n new elements.

How to modify an element in an array in ES6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

ES6 Modify an element in the array

Method 1: Access the specified element through the subscript and reassign the value

Arrays are composite data, and the array name is a reference variable pointing to the array, so the array is a reference object.

Accessing an array is accessing array elements. The elements are equivalent to variables. The elements of the array are a set of variables arranged in an orderly manner. They have no identifiers and are indexed with subscripts. The subscripts start from 0 and increase in order. Note that the array subscript is a non-negative integer expression or a character number, and cannot be other types of values ​​or expressions.

Syntax for accessing array elements and reassigning values:

数组名[指定下标值]=新值;

Example:

var arr = [1,2,3,4,5];  //声明一个数组
console.log(arr);
arr[0] = 0;  //修改第一个元素,重新赋值为0
arr[2] = "A";  //修改第三个元素,重新赋值为2
console.log(arr);

How to modify an element in an array in ES6

Method 2: Using the splice() method

The splice() method of Array array is also a very powerful method. Its function is: deletion, insertion, replacement

It should be noted that: The splice() method directly modifies the original array

We can use the replacement function of this method to modify the array elements.

Syntax:

array.splice(starti,n,值1,值2);

The actual is: delete n elements at the position of starti, and then insert the value 1 and the value 2 at this position, which can replace the original ones that were deleted Value

Example

var array = [1,2,3,4,5];  //声明一个数组
console.log(array);
array.splice(2,2,123,456);
console.log(array);

How to modify an element in an array in ES6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to modify an element in an array in ES6. 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