我有以下javascript 函数来从数组中删除一个项目,但无论我搜索什么,索引搜索总是返回-1 。我在 jQuery“on”点击函数中调用它。
function removeElement(array, elem) {
let index = array.indexOf(elem);
if (index > -1) {
array.splice(index, 1);
}
}
$('div.test').on('click', 'a.btn', function(e){
e.preventDefault();
let text = $('span.query').html().trim();
let queries = JSON.parse($('.search').val().trim());
console.log(queries); // This line shows the same results
removeElement(queries,text);
console.log(queries); // as this line
});
where$('span.query')
包含文本def
并且$('.search')
是一个输入文本字段,其中包含一个 JSON 字符串化的数组
["abc","def","ghij","klmn"]
不管用什么来搜索我的查询数组(从上面解析),索引总是-1,结果(在元素“删除”尝试之后)总是
["abc", "def", "ghij", "klmn"]
任何想法这里可能出了什么问题?我一直在为此扯头发。