【问题标题】:javascript filter and slice does not work properlyjavascript 过滤器和切片无法正常工作
【发布时间】:2018-02-22 00:54:36
【问题描述】:

我有以下代码:

conditions.slice(0).filter(condition => condition.processsteptemplate === stepId);

它应该从数组中切出一些对象。问题是 === 不匹配,所以所有元素仍在数组中...

我的失败是什么

更新:

示例代码:

var conditions = [{
      id: 14,
      conditiontype: 1,
      processsteptemplate: 9,
      deleted: false,
      processTemplate_id: 0
    },
    {
      id: 15,
      conditiontype: 1,
      processsteptemplate: 9,
      deleted: false,
      processTemplate_id: 0
    },
    {
      id: 16,
      conditiontype: 1,
      processsteptemplate: 10,
      deleted: false,
      processTemplate_id: 0
    }
  ],
  stepId = 9;
  
const output = conditions.slice(0).filter(condition => condition.processsteptemplate === stepId);
console.log(output)

【问题讨论】:

  • 为什么是conditions.slice(0).filterfilter 无论如何都会返回另一个数组。
  • 只是删除切片?
  • 试试var output = conditions.filter(x => x.processsTemplate === stepId); console.log(output)。重点是,filter 永远不会操纵您的原始数组。它将返回一个过滤值列表
  • 已经试过了...同样的结果
  • slice 在这里不起作用,因为过滤器不会改变条件数组,而是 返回一个新的:var metConditions = conditons.filter...

标签: javascript arrays reactjs


【解决方案1】:

这里删除了 processsteptemplate = 10 的数组

let arr = [
{id: 14, conditiontype: 1, processsteptemplate: 9, deleted: false, processTemplate_id: 0},
{id: 15, conditiontype: 1, processsteptemplate: 9, deleted: false, processTemplate_id: 0},
{id: 16, conditiontype: 1, processsteptemplate: 10, deleted: false, processTemplate_id: 0}
]

let step = 9;

let result = arr.filter((e) => e.processsteptemplate === step);

console.log(result);

你可能做错了什么是你假设

arr.filter((e) => e.processsteptemplate === step);

会改变当前数组中的值,这是不对的,它会返回一个新数组,现在存储在 result 中,正如您现在可以在上面的代码 sn-p 中看到的那样

【讨论】:

  • 老实说,我已经在 cmets 中解决了这个问题。此外,如果您阅读文档,可以解决此类问题。所以回答他们,是我的POV,错了。我仍然会投票,因为它确实回答了这个问题。
猜你喜欢
  • 2013-09-15
  • 2015-02-14
  • 2013-08-16
  • 2012-11-16
  • 2011-04-06
  • 1970-01-01
相关资源
最近更新 更多