[英]How do I reverse an array
Hi I have an array of strings, and I need to output them from the last one to the first one. 嗨我有一个字符串数组,我需要将它们从最后一个输出到第一个。
I don't see an arrayReverse()
function, but I'm only just learning ColdFusion 我没有看到
arrayReverse()
函数,但我只是学习ColdFusion
You can just loop over the array in reverse 你可以反过来循环遍历数组
<cfloop index="i" from="#arrayLen(myArray)#" to="1" step="-1">
<cfoutput>#myArray[i]#</cfoutput>
</cfloop>
I think you need to use Java methods to really reverse the array. 我认为你需要使用Java方法来真正反转数组。
<cfscript>
// and for those who use cfscript:
for ( var i = arrayLen( myArray ); i >= 1; i-- ) {
writeOutput( myArray[i] );
}
</cfscript>
I wrote this function to reverse an array. 我写了这个函数来反转一个数组。 It modifies the array and returns it.
它修改数组并返回它。
function init(required array arr) {
var arrLen = arrayLen(arr);
for (var i = 1; i <= (arrLen / 2); i++) {
var swap = arr[arrLen + 1 - i];
arr[arrLen + 1 - i] = arr[i];
arr[i] = swap;
}
return arr;
}
I've tested it, and it works on arrays of strings, as well as objects, etc. 我测试了它,它适用于字符串数组,以及对象等。
writeOutput(arrayReverse(['a','b','c']) ); // => ['c', 'b', 'a']
var a = ['apple', 'ball', 'cat', 'dog'];
arrayReverse(a);
writeOutput(a); // => ['dog', 'cat', 'ball', 'apple']
I put it into it's own component, so it's easier to use in different projects. 我将它放入它自己的组件中,因此在不同的项目中使用它更容易。
FYI array in CF is just an ArrayList , so... CF中的FYI数组只是一个ArrayList ,所以......
arr = [1,2,3];
createObject("java", "java.util.Collections").reverse(arr);
writeDump(arr); // arr becomes [3,2,1]
And I would not bother writing arrayReverse()
because array is passed by value in CF (not until CF2016's this.passArraybyReference
) so it's super inefficient. 而且我不打算编写
arrayReverse()
因为数组是通过CF中的值传递的(直到CF2016的this.passArraybyReference
),所以它的效率非常低。
Oh but there is an ArraySort method! 哦,但有一个ArraySort方法!
ArraySort( array, sort_type [, sort_order] );
Returns boolean. 返回布尔值。
array
is updated by reference. array
通过引用更新。
sort_type
can be numeric
, text
or textnocase
sort_type
可以是numeric
, text
或textnocase
sort_order
can be asc
or desc
sort_order
可以是asc
或desc
<cfscript>
test = [ "c", "d", "a", "b" ];
arraySort( test, 'textnocase' );
test is now:
[ "a", "b", "c", "d" ]
</cfscript>
Check out the documentation here: 查看此处的文档:
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-ab/arraysort.html https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-ab/arraysort.html
<cfscript>
test = [ "a", "b", "c", "d" ];
writeDump(listToArray(reverse(arrayToList(test))));
</cfscript>
Will do the trick. 会做的伎俩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.