当前位置:网站首页>JS how to delete an item specified in an array

JS how to delete an item specified in an array

2022-06-23 03:05:00 It workers

because js The diversity of array methods in , We can delete a specified item in many ways .

here , I will show you one of the most common methods .

Ideas as follows :

  • Get the location of the item to be deleted
  • Delete the item by location

Implementation method

Use indexOf Get the position of the element to be deleted , And then use splice Methods to remove .

splice Method by deleting existing elements and / Or add new elements to change the contents of the array .

Implementation code

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
// If the object is queried , have access to findIndex
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array);
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201242154044351.html