前端数组重新赋新值改变原数组
时间: 2023-07-03 14:26:28 浏览: 55
如果你想要重新赋新值改变原数组,可以直接对数组进行修改操作。例如:
```javascript
let arr = [1, 2, 3];
arr[0] = 4;
console.log(arr); // 输出 [4, 2, 3]
```
上述代码中,我们将数组 `arr` 的第一个元素从原来的 `1` 改为了 `4`,这样就直接改变了原数组。需要注意的是,这种方式只能修改已有的元素,不能新增或删除元素。如果想要新增或删除元素,需要使用其他方法,比如 `push()`、`pop()`、`shift()`、`unshift()` 等等。
相关问题
前端数组重新赋新值改变原数组 push方法代码
`push()` 方法可以向数组的末尾添加一个或多个元素,并返回修改后的数组的长度。例如:
```javascript
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // 输出 [1, 2, 3, 4]
```
上述代码中,我们使用 `push()` 方法向数组 `arr` 的末尾添加了一个元素 `4`,这样就修改了原数组,并返回了修改后的数组长度。
如果要向数组中添加多个元素,可以在 `push()` 方法中传递多个参数。例如:
```javascript
let arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // 输出 [1, 2, 3, 4, 5]
```
上述代码中,我们向数组 `arr` 中添加了两个元素 `4` 和 `5`,这样就修改了原数组,并返回了修改后的数组长度。
前端数组根据一个新数组去筛选
可以使用 JavaScript 中的 filter 方法来筛选数组。filter 方法可以接受一个回调函数作为参数,回调函数会遍历数组中的每个元素,如果回调函数返回 true,则该元素会被保留在返回的新数组中,否则会被过滤掉。
假设有一个原始数组 `arr`,要根据一个新数组 `filterArr` 来筛选出符合条件的元素,可以这样写:
```
const arr = [1, 2, 3, 4, 5];
const filterArr = [2, 4, 6];
const filteredArr = arr.filter(item => filterArr.includes(item));
console.log(filteredArr); // [2, 4]
```
上面的代码中,使用了 `filter` 方法和 `includes` 方法。`filter` 方法会遍历原始数组 `arr` 中的每个元素,并把符合条件的元素保留在返回的新数组 `filteredArr` 中。而 `includes` 方法会判断 `filterArr` 中是否包含当前遍历的元素 `item`,如果包含则返回 true,否则返回 false。
最终,`filteredArr` 中会保留原始数组中与 `filterArr` 中相同的元素,即 `[2, 4]`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)