One such searching function is the jQuery.inArray() function. As the name suggests, the function will determine if a specified element exists in a specified array. This utility is indispensable for javascript developers simply because of the amount of code it reduces.
Searching for elements in a javascript array often involves some kind of looping construct. In each iteration, we check if the current element is the desired element. In the case of array element deletion, we do something like this. The example below illustrates how the jQuery.inArray() function compliments the primitive splicing functionality of javascript arrays.
//Example; jQuery array deletion.
//Make the array.
var my_array=jQuery.makeArray(["A", "B", "C"])
console.log(my_array);
//Find an element to delete.
var my_pos=jQuery.inArray("B", my_array);
console.log(my_pos);
//Delete the element only if it exists.
my_pos < 0 || my_array.splice(my_pos, 1);
console.log(my_array);
No comments :
Post a Comment