Javascript TypeError:无法读取undefined的属性'indexOf' [英] Javascript TypeError: Cannot read property 'indexOf' of undefined
问题描述
在此代码中,我想从 cart_products
数组中删除一个元素。
In this code I want to remove an element from the cart_products
array.
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
$.each(cart_products,function(key, item) {
if(item.indexOf(product+"^") !== -1){
cart_products.splice(key, 1);
}
});
但我在谷歌Chrome控制台中收到此错误:
But I get this error in Google Chrome console:
Uncaught TypeError:无法读取未定义的属性'indexOf'
Uncaught TypeError: Cannot read property 'indexOf' of undefined
是否有问题代码?
感谢您的帮助。
推荐答案
问题在于你当jQuery的 $。每个
循环遍历它时,重新修改数组,所以当它到达结尾时,以前的条目在索引2不再存在。 (我承认我有点惊讶 $。每个
表现得那样,但我没有使用 $。每个
至少五年,所以...)
The problem is that you're modifying the array while jQuery's $.each
is looping over it, so by the time it gets to the end, the entry that used to be at index 2 is no longer there. (I admit I'm a bit surprised $.each
behaves that way, but I haven't used $.each
in at least five years, so...)
如果目标是从阵列中删除匹配,那么更好的选择是< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter =noreferrer> filter
:
If the goal is to remove matches from the array, the better choice is filter
:
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
cart_products = cart_products.filter(function(item) {
return item.indexOf(product+"^") === -1;
});
console.log(cart_products);
...或者如果是重要的是就地修改阵列而不是创建一个新的使用无聊的用于
循环正如Andreas指出的那样通过数组循环向后所以它没有移除东西时很重要:
...or alternately if it's important to modify the array in-place rather than creating a new one use a boring for
loop as Andreas points out looping backward through the array so it doesn't matter when you remove things:
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
var target = product + "^";
for (var index = cart_products.length - 1; index >= 0; --index) {
if (cart_products[index].indexOf(target) !== -1) {
cart_products.splice(index, 1);
}
}
console.log(cart_products);
这篇关于Javascript TypeError:无法读取undefined的属性'indexOf'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!