Method: 1. Use splice() to delete, add or replace elements, the syntax is "array.splice(subscript, number of elements, new value 1,..., new value X)"; 2. Re-copy the specified subscript element with the syntax "array name [subscript value] = new value;"; 3. Use replaceAll() to replace all specific elements with the syntax "str=arr.toString().replaceAll(" Search value","new value");newArr=str.split(",");".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Several ways to modify array values
Method 1: Use the splice() method
Use the splice() method to delete elements, add elements or replace elements
array.splice(index,howmany,item1,.....,itemX)
Parameters | Description |
---|---|
index | Required. Specifies where to add/remove elements. This parameter is the subscript of the array element to start inserting and/or deleting, and must be a number. |
howmany | Optional. Specifies how many elements should be removed. Must be a number, but can be "0". If this parameter is not specified, all elements starting from index to the end of the original array will be deleted. |
item1, ..., itemX | Optional. New elements to be added to the array |
Return value: an array composed of all deleted elements. If no elements are deleted, an empty array will be obtained
Example 1:
var arr = [1,2,3,4,5,6,7,8,9,10]; console.log(arr); //删除 arr.splice(1,2); console.log(arr); //打印:[1,4,5,6,7,8,9,10]
Example 2:
var arr = [1,2,3,4,5,6,7,8,9,10]; console.log(arr); //替换 arr.splice(1,2,'b','c'); console.log(arr); //打印:[1, "b", "c", 6, 7, 8, 9, 10]
Example 3:
var arr = [1,2,3,4,5,6,7,8,9,10]; console.log(arr); //添加,如果不删除元素,但是又存在第三个或者3+的参数,就会有添加的功能 arr.splice(1,0,'a','b','c'); console.log(arr); //打印:[1, "a", "b", "c", "b", "c", 6, 7, 8]
Method 2: Access the specified element through the subscript and re-copy it
Syntax for accessing the array element and re-assigning the value:
数组名[指定下标值]=新值;
The example is as follows:
var arr = [1,2,3,4,5]; //声明一个数组 console.log(arr); arr[0] = 0; //修改第一个元素,重新赋值为0 arr[2] = "A"; //修改第三个元素,重新赋值为2 console.log(arr);
Method 3: Use replaceAll() to replace all specific elements
replaceAll is Used to replace characters in a string. Of course, when we convert "array" and "string", it can also be applied to arrays. Generally used with regular expressions.
const newStr = str.replaceAll(regexp|substr, newSubstr|function)
Example:
var arr = [3, 5, "-", "9", "-"]; var newArr = []; var str = arr.toString().replaceAll("-","新"); //数组转字符串并替换所有特定元素 console.log(str); //3,5,新,9,新 newArr = str.split(","); //字符串转数组 console.log("newArr",newArr); //newArr (5) ["3", "5", "新", "9", "新"]
javascript video tutorial, programming video 】
The above is the detailed content of How to modify the value of an array in es6. For more information, please follow other related articles on the PHP Chinese website!