// 判断数组有没有特定的参数,有个话就移除例如[3,2,2,3]
var removeElement = function(nums, val) {
return nums.filter(item => item !== val);
};
const array = [3, 2, 2, 3];
const element = 2;
const result = removeElement(array, element);
console.log(result); // 输出 [3, 3]
//---------------------------------------------------------------
// 删除数组第一个元素
// 1-1 删除第一个元素
let arrayShift = ['a',4,1]
arrayShift.shift()
console.log(arrayShift)
// 1-2 删除第一个元素,slice不会改变原数组
let arraySlice = ['a',4,1]
let newArr = arraySlice.slice(1)
console.log(newArr)
// 1-3 删除第一个元素
// arrSplice => [2,3,4,5] newArrSplice => [1]
let arrSplice = [1,2,3,4,5]
let newArrSplice = arrSplice.splice(0, 1)
console.log('newArrSplice==>',newArrSplice)
//---------------------------------------------------------------
// 删除数组最后一个元素
let arrd = [1,2,3,4,5]
arrd.pop() // 5
// arrd => [1,2,3,4]
let arrd2 = [1,2,3,4,5]
let newArrd2 = arrd2.slice(0, arrd2.length - 1)
// arrd2 => [1,2,3,4,5] newArrd2 => [1,2,3,4]
let arrd3 = [1,2,3,4,5]
let newArrd3 = arrd3.splice(arrd3.length - 1, 1)
// arrd3 => [1,2,3,4] newArrd3 => [5]
//---------------------------------------------------------------
// 删除数组中指定下表元素
let index = 3 // 删除的下表
let arrid = [1,2,9,4,5]
arrid.splice(index, 1) // [4]
// arrid => [1,2,9,5]
let arrid2 = [1,2,9,4,5]
arrLen = arrid2.length,
newArrid = [];
for (let i = 0; i < arrLen; i++) {
if (i !== index) {
newArrid.push(arrid2[i])
}
}
// arrid2 => [1,2,9,4,5] newArrid => [1,2,9,5]
let arrid3 = [1,2,3,4,5]
delete arrid3[index]
// arrid3 = > [1, 2, 3, empty, 5]
// 提供了一个delete关键字用来删除(清除)数组元素。
// 注意:使用delete删除元素之后数组长度不变,
// 只是被删除元素被置为empty了。
//---------------------------------------------------------------
// 删除数组中某个指定元素
let value = 'b'
// splice 删除---改变元素值
let arr2 = ['a','b','c','d']
arr2.splice(arr2.indexOf(value), 1) // ['b']
console.log('arr2==>',arr2)
// filter 删除---改变原数组
let arr3 = ['a','b','c','d']
arr3 = arr3.filter(item => item != value)
console.log('arr3==>',arr3)
// Set 删除---不改变原数组
let arr4 = ['a','b','c','d']
let newSet4 = new Set(arr4)
newSet4.delete(value)
let newArr4 = [...newSet4]
console.log('newArr4==>',newArr4,arr4)
console