Home > Web Front-end > Front-end Q&A > jquery deletes specified value from array

jquery deletes specified value from array

王林
Release: 2023-05-25 12:06:37
Original
1195 people have browsed it

During the development process, array operations are often required. Deleting a specified value in an array is a common requirement. This article will introduce how to use jQuery to delete specified values ​​in an array.

First, we need to prepare an array:

var arr = [1, 2, 3, 4, 5];
Copy after login

Then, we need to define a function to delete the specified value:

function deleteValue(arr, value) {
  while ($.inArray(value, arr) !== -1) {
    arr.splice($.inArray(value, arr), 1);
  }
  return arr;
}
Copy after login

The logic of this function is very simple, first use jQuery $.inArray() function in to find the position of the specified value in the array. If the value is found, it is removed from the array using the splice() function. Finally, the deleted array is returned.

Next, we can delete the specified value in the array by calling the deleteValue() function:

var arr = [1, 2, 3, 4, 5];
arr = deleteValue(arr, 3); // 删除数组中的值为3的元素
console.log(arr); // 输出 [1, 2, 4, 5]
Copy after login

After the code is executed, the output result is [1, 2, 4, 5], Description: The function successfully deleted the element with value 3 from the array.

In addition to using custom functions, we can also use the $.grep() function in jQuery to delete specified values ​​in the array:

var arr = [1, 2, 3, 4, 5];
arr = $.grep(arr, function(value) {
  return value !== 3;
});
console.log(arr); // 输出 [1, 2, 4, 5]
Copy after login

The logic of this function is also very simple. First, use the $.grep() function to filter out elements in the array that are not equal to the specified value, and finally return the filtered array.

However, it should be noted that the array filtered by the $.grep() function does not change the original array, but returns a new array, so it needs to be assigned to the original array variable.

To sum up, this article introduces how to use jQuery to delete specified values ​​in an array. Whether you use a custom function or the $.grep() function in jQuery, it is very simple and easy to understand, and it is a very practical skill for array operations.

The above is the detailed content of jquery deletes specified value from array. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template