在JavaScript中使用Array.map去除元素 [英] Removing elements with Array.map in JavaScript
问题描述
我想通过使用 map()
函数过滤一组项目。这里是一个代码片段:
var filteredItems = items.map(function(item)
{
如果(...某些条件...)
{
退货项目;
}
});
问题是滤出的项目仍然使用数组中的空格,我想完全擦除它们。
任何想法?
编辑:谢谢,我忘了 filter( )
,我想要的实际上是一个 filter()
然后是一个 map()
。
编辑2:感谢您指出 map()
和 filter()
并未在所有浏览器中实现,但我的具体代码并不打算在浏览器中运行。 应该使用过滤器
方法,而不是映射,除非要过滤数组中的项。
<例如。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ $ ..某些条件...;
});
I would like to filter an array of items by using the map()
function. Here is a code snippet:
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.
Any idea?
EDIT: Thanks, I forgot about filter()
, what I wanted is actually a filter()
then a map()
.
EDIT2: Thanks for pointing that map()
and filter()
are not implemented in all browsers, although my specific code was not intended to run in a browser.
You should use the filter
method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
var filteredItems = items.filter(function(item)
{
return ...some condition...;
});
[Edit: Of course you could always do sourceArray.filter(...).map(...)
to both filter and mutate]
这篇关于在JavaScript中使用Array.map去除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!