react中数组的操作

发布时间 2023-12-01 23:33:06作者: 老鲜肉

添加元素:你可以使用push方法来在数组的末尾添加一个元素,或者使用unshift方法来在数组的开头添加一个元素。你也可以使用concat方法或者扩展运算符...来合并两个数组。

let arr = [1, 2, 3];
arr.push(4); // arr is now [1, 2, 3, 4]
arr.unshift(0); // arr is now [0, 1, 2, 3, 4]
arr = arr.concat([5, 6]); // arr is now [0, 1, 2, 3, 4, 5, 6]
arr = [...arr, 7, 8]; // arr is now [0, 1, 2, 3, 4, 5, 6, 7, 8]

 删除元素:你可以使用pop方法来删除数组的最后一个元素,或者使用shift方法来删除数组的第一个元素。你也可以使用splice方法来删除数组中的特定元素。

let arr = [0, 1, 2, 3, 4];
arr.pop(); // arr is now [0, 1, 2, 3]
arr.shift(); // arr is now [1, 2, 3]
arr.splice(1, 1); // arr is now [1, 3]

遍历元素:你可以使用map方法来遍历数组并返回一个新的数组,或者使用forEach方法来遍历数组并执行某个操作。

let arr = [1, 2, 3];
let newArr = arr.map(x => x * 2); // newArr is [2, 4, 6]
arr.forEach(x => console.log(x)); // logs 1, 2, 3