一、JS數組刪除指定元素c
在JS數組中刪除指定元素c可以使用filter函數,該函數會返回新的數組,而不會改變原有的數組。該方法的具體實現如下:
let arr = ['a', 'b', 'c', 'd', 'e']; let c = 'c'; let newArr = arr.filter(function(item) { return item !== c; }); console.log(newArr); // ["a", "b", "d", "e"]
以上代碼會從數組中刪除值為c的元素,並返回新的數組newArr。
二、JS數組對象刪除指定元素
如果數組是一個對象數組,則可以使用findIndex方法查找元素的位置,再使用splice方法刪除元素。代碼如下:
let arr = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}]; let id = 3; let index = arr.findIndex(function(item) { return item.id === id; }); if (index !== -1) { arr.splice(index, 1); } console.log(arr); // [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 4, name: 'd'}]
以上代碼會在對象數組中刪除id為3的元素。
三、JS數組刪除指定元素方法
除了使用filter和splice方法外,JS還提供了許多其它的方法來刪除指定元素,如pop方法,shift方法等。這裡介紹一些常用的方法:
pop方法:
pop方法刪除數組最後一個元素並返回該元素的值,如下所示:
let arr = ['a', 'b', 'c', 'd', 'e']; let last = arr.pop(); console.log(last); // "e" console.log(arr); // ["a", "b", "c", "d"]
shift方法:
shift方法刪除數組第一個元素並返回該元素的值,如下所示:
let arr = ['a', 'b', 'c', 'd', 'e']; let first = arr.shift(); console.log(first); // "a" console.log(arr); // ["b", "c", "d", "e"]
四、JS數組刪除指定元素改變原數組
如果需要改變原數組,可以使用forEach方法。代碼如下:
let arr = ['a', 'b', 'c', 'd', 'e']; let c = 'c'; arr.forEach(function(item, index, arr) { if (item === c) { arr.splice(index, 1); } }); console.log(arr); // ["a", "b", "d", "e"]
以上代碼會刪除數組中的值為c的元素,同時改變原數組。
五、JS數組刪除指定元素splice
splice方法可以刪除數組中指定位置的元素,並返回被刪除的元素數組。代碼如下:
let arr = ['a', 'b', 'c', 'd', 'e']; let startIndex = 2; let deleteCount = 1; let deletedItems = arr.splice(startIndex, deleteCount); console.log(deletedItems); // ["c"] console.log(arr); // ["a", "b", "d", "e"]
以上代碼會刪除數組中的第三個元素(從0開始計數),並返回被刪除的元素’c’。
六、JS數組刪除指定元素返回新數組
除了使用filter方法外,也可以使用slice方法返回一個新的數組。代碼如下:
let arr = ['a', 'b', 'c', 'd', 'e']; let c = 'c'; let startIndex = arr.indexOf(c); let deletedItems = arr.slice(0, startIndex).concat(arr.slice(startIndex + 1)); console.log(deletedItems); // ["a", "b", "d", "e"]
以上代碼會刪除數組中的值為c的元素,並返回新的數組deletedItems。
七、React數組刪除指定元素
React中的數組刪除指定元素和JS無異。可以使用上述提到的方法來實現。例如,可以使用filter方法刪除指定元素並更新組件狀態:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: ['a', 'b', 'c', 'd', 'e']
};
}
handleClick() {
let c = 'c';
let newArr = this.state.arr.filter(function(item) {
return item !== c;
});
this.setState({arr: newArr});
}
render() {
return ({this.state.arr.map(item =>
{item}
)}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/243092.html