问题描述
我的遍历数组的和基于条件的我的要删除该阵列基于索引的特定元素(目前我使用)的。以下是我的code预期这是完美的工作。
I'm iterating an array and based on a condition I want to delete the specific element from that array based on index(currently I use). Following is my code which is working perfectly as expected.
var todayWeekNo = new Date().getWeek();
$.each(arr, function (i, j) {
var isEqual = todayWeekNo == new Date(j.Date).getWeek();
if (isEqual) {
delete arr[i];
}
});
您可以看到这个
You can see this working fiddle
在寻找一种更好的方法,我才知道,
While looking for a better approach, I came to know that
所以我换成删除改编[I];
是 arr.splice(I,1);
So I replaced delete arr[i];
with arr.splice(i, 1);
有关第2迭代它是工作的罚款,而它卡住在最后一次迭代。
For first 2 iteration it was working fine, whereas it get stuck at the last iteration.
以下是控制台消息():
Below is console message(jsfiddle):
index0 arr: [object Object] (index):43
index1 arr: [object Object] (index):43
index2 arr: undefined (index):43
Uncaught TypeError: Cannot read property 'Date' of undefined
请一些线索这一问题。
推荐答案
$每次obvously不处理数组的修改,我不知道的(I< arr.length)确实不是,ID,而尝试:
$.each is obvously not handling the modification of the array, i am not sure for (i < arr.length) does either, id rather try:
for (i in arr) {
console.log("index" + i + " arr: " + arr[i]);
var isEqual = todayWeekNo == new Date(arr[i].Date).getWeek();
if (isEqual) {
arr.splice(i, 1);
}
}
这篇关于无法在使用数组剪接删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!