本文介绍了从数组中删除负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array coming from the database grabbing all the id's from a group of elements. However it seems to also be grabbing some negative id's from some backend stuff happening and it's breaking what I need to do with these id's.

有没有办法去除这些负面在我循环播放并将其放入应用程序之前,数组中的id是什么?

Is there a way to remove these negative id's from the array before I loop it and put it in the app?

我抓住它们之后我已经遍历它们了。

After I grab them I'm already looping through them.

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

我已经尝试在那里添加一个if语句,如果id小于0,但似乎不想工作。

I have tried adding an if statement in there to just not run that code if the id is less than 0, but that didn't seem to want to work.

推荐答案

只需使用 Array.filter

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

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

Array.filter filters the elements based on the boolean returned. Here we filter only numbers which are greater than -1

这篇关于从数组中删除负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 07:51