Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jQuery删除数组中的第一个出现_Jquery_Arrays - Fatal编程技术网

使用jQuery删除数组中的第一个出现

使用jQuery删除数组中的第一个出现,jquery,arrays,Jquery,Arrays,我试图从数组中删除第一次出现的元素,而不是像搜索的元素那样的所有元素 该数组类似于: groupedObjects: [ { value: 125, currency: "EUR" }, { value: 100, currency: "USD" }, { value: 100, currency: "USD" }, { value: 320, currency: "RON" } ] 我用来解决这个问题的代码是: var newArr = $.grep(am

我试图从数组中删除第一次出现的元素,而不是像搜索的元素那样的所有元素 该数组类似于:

groupedObjects: [
    { value: 125, currency: "EUR" }, 
    { value: 100, currency: "USD" },
    { value: 100, currency: "USD" }, 
    { value: 320, currency: "RON" }
]
我用来解决这个问题的代码是:

var newArr = $.grep(amount, function(item, idx) {
    return item.currency == currency || item.value == val; }, true);
amount = newArr;
此代码的问题在于,使用它时,它将删除找到的所有事件,而不仅仅是第一个 有人能帮我吗

$.each(amount, function(idx, item) {
    if (item.currency == currency || item.value == val) {
        amount.splice(idx, 1); // Remove current item
        return false; // End the loop
    }
});

你必须这样做

groupedObjects.拼接(0,1)


看看那里

你只需返回
newArr[0]
很抱歉,这不是我想要的答案,它必须是动态的,想想一个最多有1000个元素的数组。从我可以确定的情况来看,从当前循环中的数组中删除可能非常危险,因为元素[1]变成了元素[0]删除后等等。而且,我已经尝试了这段代码,但没有成功。如果继续循环数组,这是一个问题。但是,由于它在删除元素后退出循环,所以这不应该是一个问题。我现在已经测试过了,请看演示。谢谢,现在它可以工作了,我已经将代码放入我的应用程序中。我也试过,但没有“返回错误;”很明显,它没有起作用。如果要使用循环中的“拼接”删除所有匹配元素,则需要从最高索引删除到0。这样重新编号就不会打乱循环。