Home >Web Front-end >Front-end Q&A >How to change array data in es6
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;".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
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]);
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);
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
Method 2: Access specified elements through subscripts
Syntax for accessing array elements and reassigning values:
数组名[指定下标值]=新值;
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);
Output results;
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!