bcm*_*bcm 36 javascript jquery
如何在项目到达时从项目中删除项目[i]:
$.each(items, function(i) {
// how to remove this from items
});
Run Code Online (Sandbox Code Playgroud)
lon*_*day 117
$.each在这种情况下最好不要使用.请$.grep改用.这循环遍历一个数组,其方式$.each与一个例外完全相同.如果true从回调返回,则保留该元素.否则,它将从阵列中删除.
您的代码应如下所示:
items = $.grep(items, function (el, i) {
if (i === 5) { // or whatever
return false;
}
// do your normal code on el
return true; // keep the element in the array
});
Run Code Online (Sandbox Code Playgroud)
还有一点需要注意:this在$.grep回调的上下文中设置window,而不是数组元素.
Dav*_*ang 10
我猜你想要的$.map.您可以return null删除项目,而不必担心索引可能会如何移动:
items = $.map(items, function (item, index) {
if (index < 10) return null; // Removes the first 10 elements;
return item;
});
Run Code Online (Sandbox Code Playgroud)
如果要从数组中删除元素,请使用 splice()
var myArray =['a','b','c','d'];
var indexToRemove = 1;
// first argument below is the index to remove at,
//second argument is num of elements to remove
myArray.splice(indexToRemove , 1);
Run Code Online (Sandbox Code Playgroud)
myArray 现在将包含 ['a','c','d']
| 归档时间: |
|
| 查看次数: |
44533 次 |
| 最近记录: |