There are many ways to delete elements from js arrays, including using the splice() method, using the pop() and shift() methods, using the delete keyword, and using the filter() method. wait. The following will introduce you to these methods in detail and provide specific code examples.
The sample code is as follows:
let fruits = ['apple', 'banana', 'orange', 'grape']; fruits.splice(1, 2); // 从索引为1的元素开始删除2个元素 console.log(fruits); // 输出:['apple', 'grape']
The sample code is as follows:
let fruits = ['apple', 'banana', 'orange', 'grape']; fruits.pop(); // 删除最后一个元素 console.log(fruits); // 输出:['apple', 'banana', 'orange'] fruits.shift(); // 删除第一个元素 console.log(fruits); // 输出:['banana', 'orange']
The sample code is as follows:
let fruits = ['apple', 'banana', 'orange', 'grape']; delete fruits[1]; // 删除索引为1的元素 console.log(fruits); // 输出:['apple', undefined, 'orange', 'grape']
The sample code is as follows:
let fruits = ['apple', 'banana', 'orange', 'grape']; fruits = fruits.filter(function(fruit) { return fruit !== 'banana'; // 删除值为'banana'的元素 }); console.log(fruits); // 输出:['apple', 'orange', 'grape']
The above are the specific instructions and sample codes for several methods of deleting elements from js arrays. Different methods are suitable for different scenarios, and you can choose the appropriate method according to your needs when using it.
The above is the detailed content of What are the methods to delete elements from js array. For more information, please follow other related articles on the PHP Chinese website!