1

I need to multiple an array by a number (2) using Coldfusion.

For ex: myArray = [1,2,3,4]

multiply each element by a number 2

I know there is a map method to do so, but wasn't sure how it would work in Coldfusion. Is there a function to do this? or will need to write a custom function/method for this?

4

4 回答 4

4

使用 CFScript

<cfscript>
for(var item in myArray) 
    { 
    myArray[item] *= 2; 
    }
</cfscript> 

或者,如果您想保留原件

<cfscript>
newArray = myArray;   

for(var item in newArray) 
    { 
    newArray[item] *= 2; 
    }
</cfscript> 
于 2013-11-05T21:32:26.473 回答
4

如果您使用的是 ColdFusion 10,则可以使用arrayEach()

<cfscript>
original = [1,2,3,4];
multiplied = [];
arrayEach(original, function(e){
    arrayAppend(multiplied, e * 2);
});

writeDump(var=[original, multiplied]);
</cfscript>
于 2013-11-05T22:08:27.687 回答
2

尽管 CF 10 或 Railo 4 中不存在 map 函数,但您可以使用Underscore.cfc 库中的map 函数

_ = new Underscore(); // init library

result = _.map([1, 2, 3, 4], function(val) {
   return val * 2;
});

注意:我写了 Underscore.cfc

于 2013-11-06T01:24:17.043 回答
0

您必须编写自己的函数。听起来您可能已经掌握了如何做到这一点 - 但是,如果它有帮助,我将如何实现它:

<cffunction name="ArrayMultiply" >
    <cfargument name="SourceArray" type="array" >
    <cfargument name="Factor" type="numeric" >
    <cfset NewArray = ArrayNew(1) >
    <cfloop index="i" from="1" to="#ArrayLen(ARGUMENTS.SourceArray)#" >
        <cfset NewArray[i] = ARGUMENTS.SourceArray[i] * ARGUMENTS.Factor >
    </cfloop>
    <cfreturn NewArray >
</cffunction>

<cfset MyArray = ArrayNew(1) >
<cfset MyArray[1] = 1 >
<cfset MyArray[2] = 2 >
<cfset MyArray[3] = 3 >
<cfset MyArray[4] = 4 >

<cfset MultipliedArray = ArrayMultiply( MyArray, 2 ) >

<cfoutput>
    <p>[ #MultipliedArray[1]#, #MultipliedArray[2]#, #MultipliedArray[3]#, #MultipliedArray[4]# ]</p>
</cfoutput>
于 2013-11-05T21:29:21.427 回答