【问题标题】:Array.Filter not woking [duplicate]Array.Filter 不起作用[重复]
【发布时间】:2020-12-26 06:05:15
【问题描述】:

当我运行一个数组时。 filter 函数,它返回所有数组内容而不执行条件检查。请帮助。谢谢

这里是代码

const paragraphFields = ['a', 'b', 'c', 'd', 'ff', 'g'];
 const handleDeleteParagraphFields = (array_index) => {
        paragraphFields.filter((_, index) => index !== array_index);
        console.log(paragraphFields);
        return paragraphFields;
    };
handleDeleteParagraphFields(2)

这是输出

[
"a",
"b",
"c",
"d",
"ff",
"g"
]

【问题讨论】:

  • 你忘了传递参数,所以array_index 是undefined
  • @CertainPerformance,我添加参数时是一样的。这是我的帖子中的一个遗漏,我添加了它。请帮助仔细研究问题
  • 您应该存储过滤器返回的输出。 const paragraphFields = ['a', 'b', 'c', 'd', 'ff', 'g']; const handleDeleteParagraphFields = (array_index) => { var newArray = paragraphFields.filter((_, index) =>{ return index !== array_index; }); console.log(newArray); return newArray; }; handleDeleteParagraphFields(2)
  • 如果你只是想从索引中删除一些东西,为什么不使用 array.splice(index, 1) ?

标签: javascript arrays data-structures filter


【解决方案1】:

Array filter() 在新数组中返回结果,而不是在原地修改数据:

return paragraphFields.filter((_, index) => index !== array_index);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 2022-01-08
    • 1970-01-01
    • 2018-01-04
    • 2013-08-11
    • 2017-07-19
    • 2015-07-04
    • 2012-10-26
    相关资源
    最近更新 更多