使用js箭头函数作为参数

时间:2016-10-13 09:32:56

标签: javascript ecmascript-6

我使用箭头功能将参数传递给其他功能。看起来有点像这样:

someFunction(parameter1, () => {
  return model.associatedGroups.filter(group => {
    return group.isAssociated === true;
   })
}, parameter3)

但是当我调试它时,我正在接收一个函数,该方法是调用而不是过滤数组。我应该怎么写它才能找回过滤后的数组?

2 个答案:

答案 0 :(得分:1)

您只是传递对函数的引用。

调用函数将结果作为参数传递:

<ns0:Takeoff xmlns="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://download.autodesk.com/us/navisworks/schemas/nw-TakeoffCatalog-10.0.xsd">
        <ns0:Catalog>
            <ns0:Item CatalogId="f9f30bfc-6c43-4b7b-a335-5c5c093b4165" Color="-3887691" LineThickness="0.1" Name="Column Location D" Transparency="0.3" WBS="1">
                <ns0:VariableCollection>
                    <ns0:Variable Formula="=ModelLength" Name="Length" Units="Meter" />
                    <ns0:Variable Formula="=ModelWidth" Name="Width" Units="Meter" />
                    <ns0:Variable Formula="=ModelThickness" Name="Thickness" Units="Meter" />
                    <ns0:Variable Formula="=ModelHeight" Name="Height" Units="Meter" />
                    <ns0:Variable Formula="=ModelPerimeter" Name="Perimeter" Units="Meter" />
                    <ns0:Variable Formula="=ModelArea" Name="Area" Units="SquareMeter" />
                    <ns0:Variable Formula="=ModelVolume" Name="Volume" Units="CubicMeter" />
                    <ns0:Variable Formula="=ModelWeight" Name="Weight" Units="Kilogram" />
                    <ns0:Variable Formula="=1" Name="Count" />
                </ns0:VariableCollection>
            </ns0:Item>
        </ns0:Catalog>
        <ns0:ConfigFile>
            <Workbook noNamespaceSchemaLocation="http://download.autodesk.com/us/navisworks/schemas/nw-TakeoffConfiguration-10.0.xsd">
</Workbook>
    </ns0:ConfigFile>
</ns0:Takeoff>

或者只是传递过滤器的结果:

someFunction(
  parameter1, 
  (() => model.associatedGroups.filter(group => group.isAssociated === true))(), 
  parameter3
)

或者按原样传递函数并在someFunction( parameter1, model.associatedGroups.filter(group => group.isAssociated === true), parameter3 ) 内调用它以获得结果。

答案 1 :(得分:0)

这是因为你传递了一个函数,而不是一个数组。如果你想要这个函数的结果,你必须调用它。

此外,使用箭头功能,如果只有一行,则不需要放回`。

试试这个:

someFunction(parameter1, (() => model.associatedGroups.filter(group => group.isAssociated === true))(), parameter3)

编辑:这是应该的:)

someFunction(parameter1, model.associatedGroups.filter(group => group.isAssociated === true), parameter3)