Home > Web Front-end > Front-end Q&A > How to change array data in es6

How to change array data in es6

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2022-04-26 10:08:07
Original
2742 people have browsed it

Change method: 1. Use the splice() method to modify. This method can directly modify the contents of the original array. The syntax is "array.splice (starting position, modified number, modified value)"; 2 , use subscripts to access array elements, and reassign values ​​to modify array data. The syntax is "array [subscript value] = modified value;".

How to change array data in es6

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

How to change array data in es6

Method 1: Use the splice() method

splice() method to change the contents of the array and delete the old elements When adding new elements.

Syntax

array.splice(index, howMany, [element1][, ..., elementN]);
Copy after login

Parameter Details

  • index - Start changing the index of the array.

  • howMany - An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

  • element1, ..., elementN - The element to add to the array. If no elements are specified, splice simply removes elements from the array.

Return Value

Returns the extracted array based on the passed parameters.

Example

var arr = ["orange", "mango", "banana", "sugar", "tea"];  
var removed = arr.splice(2, 0, "water");  
console.log("After adding 1: " + arr );  
console.log("removed is: " + removed); 
removed = arr.splice(3, 1);  
console.log("After adding 1: " + arr );  
console.log("removed is: " + removed);
Copy after login

When compiled, it will generate the same code in JavaScript.

Output

After adding 1: orange,mango,water,banana,sugar,tea 
removed is:  
After adding 1: orange,mango,water,sugar,tea 
removed is: banana
Copy after login

Method 2: Access specified elements through subscripts

Syntax for accessing array elements and reassigning values:

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

Examples are as follows:

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

Output results;

How to change array data in es6

##[Related recommendations:

javascript video tutorial, web front end

The above is the detailed content of How to change array data in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template