I have found two ways. Which one is better? Is there any other way better than these two?
myArray.splice($.inArray(id, myArray),1);
or
myArray.splice(myArray.indexOf(id),1);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Neither option is safe because both will remove the last element from the array if
idisn’t found.Whether you use
$.inArray()or.indexOf()you’ll get a return of-1ifidisn’t in the array, and when you pass-1to the.splice()method it will remove the last item from the array.So really you should say:
Obviously you can encapsulate the above in a function of your own if desired.
As for which of
$.inArray()and.indexOf()is better, that depends on whether you care about supporting older browsers (mainly IE8 and less) that don’t support.indexOf(). You should care if your code is on a public website, since a lot of people still use IE8 and IE7. If you’re already using jQuery you might as well stick with$.inArray(), otherwise use the.indexOf()shim at MDN.