从数组中删除负数

Remove negative numbers from array

本文关键字:删除 数组      更新时间:2023-09-26

我有一个来自数据库的数组,从一组元素中获取所有id。但是,它似乎也从一些后端发生的事情中获取了一些负id,并且它破坏了我需要对这些id做的事情。

有没有办法在我循环它并将其放入应用程序之前从数组中删除这些负 id?

我抓住它们之后,我已经在循环它们了。

ids.forEach(function(Id) {
            //Code adding elements matching with id's to the screen
});

我尝试在其中添加一个 if 语句,以便在 id 小于 0 时不运行该代码,但这似乎不想工作。

只需使用Array.filter

ids = ids.filter(function(x){ return x > -1 });

Array.filter 根据返回的布尔值过滤元素。在这里,我们只过滤大于-1的数字

使用带有箭头函数的 Array.filter。

ids = ids.filter( x => x > -1 ); 

使用 grep:

ids = [-1,3,4,-2]
ids = jQuery.grep(ids, function( n, i ) {
  return n>=0;
});
console.log(ids)

说明:查找满足筛选器函数的数组元素。原始阵列不受影响。