jquery版本的array.contains

mor*_*des 55 javascript jquery

jQuery可以测试数组是否存在对象(作为核心功能的一部分还是通过可用的插件)?

此外,我正在寻找类似的东西array.remove,它将从数组中删除给定的对象.jQuery可以为我处理这个吗?

Pre*_*aul 91

jQuery.inArray返回与您搜索的项匹配的第一个索引,如果未找到,则返回-1:

if($.inArray(valueToMatch, theArray) > -1) alert("it's in there");
Run Code Online (Sandbox Code Playgroud)

你不应该需要一个array.remove.使用拼接:

theArray.splice(startRemovingAtThisIndex, numberOfItemsToRemove);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用jQuery.grep util 执行"删除" :

var valueToRemove = 'someval';
theArray = $.grep(theArray, function(val) { return val != valueToRemove; });
Run Code Online (Sandbox Code Playgroud)

  • 还有:theArray.splice($.inArray(value,theArray),1); (4认同)