如何像3*3矩阵一样在coldfusion中打印矩阵,我是coldfusion中的新成员,num = 1,2,3,4,5,6,7,8,9;这是我的数组--如何通过编程打印这个数组的3行3列。矩阵输出为`
1 4 7
2 5 8
3 6 9如何在coldfusion中创建这样的矩阵
发布于 2022-01-01 22:51:27
我们仍然不知道你是如何存储矩阵数据的。因此,我正在创建一个简单的示例,说明存储矩阵数据的方法以及如何将其输出到HTML中。这只是一个例子,说明我将如何做,虽然可能有其他方式。
存储矩阵数据:首先需要将矩阵的所有数据存储在一起,这样就可以轻松地对所有值进行迭代(循环),从而能够逐行、逐列地直接寻址每个值。用于这类任务的一个常见实践是数组数组,@James已经对此进行了注释。这些只是存储在数组中的数组!
作为cfscript的代码示例,以获得更好的解释:
<cfscript>
// create empty matrix array to store a matrix
myMatrix2DArray=[];
// setting the values row by row with
// myMatrix2DArray[rowIndex]=[ valueOfColumn1, valueOfColumn2, valueOfColumn3];
myMatrix2DArray[1]=[1,4,7];
myMatrix2DArray[2]=[2,5,8];
myMatrix2DArray[3]=[3,6,9];
writedump( var=myMatrix2DArray, label="example1" );
</cfscript>存储相同数据的隐式方法:
<cfscript>
//setting multidimensional array (2D) fully implicitly (example 2)
myMatrix2DArray=[
[1,4,7],
[2,5,8],
[3,6,9]
];
writedump( var=myMatrix2DArray, label="example2" );
</cfscript>从上面的示例中可以看到,矩阵将每一行存储在一个数组(维度1)中,并为列值存储一个额外的数组(维度2):因此,数组的数组-在我们的示例中是一个2D数组。
因为你已经更新了你的问题,把数据作为一维数组提供给我们,我会先把它变成二维数组。
是使用for循环的典型方式:
<cfscript>
//using classic for loop:
initialArray=[1,4,7,2,5,8,3,6,9];
row=[];
myMatrix2DArray=[];
arrayIndex=1;
for( element in initialArray ){
if( arrayIndex mod 3 == 0 ){
//append last element;
row.append( element );
myMatrix2DArray.append( row );
//reset row and return acc with 1;
row=[];
arrayIndex=1;
}else{
row.append( element );
arrayIndex++;
}
}
</cfscript> 使用arrayReduce()函数的新方法(我在这里使用成员函数):
<cfscript>
// using arrayReduce() member function
initialArray=[1,4,7,2,5,8,3,6,9];
row=[];
myMatrix2DArray=[];
initialArray.reduce(
( acc, element ) => {
if( acc mod 3 == 0 ){
//append last element;
row.append( element );
myMatrix2DArray.append( row );
//reset row and return acc with 1;
row=[];
return 1;
}else{
row.append( element );
return acc+1;
}
}, 1 );
writedump( var=myMatrix2DArray, label="example3" );
</cfscript>将矩阵数据输出为HTML :将数据存储为二维数组,我们可以很容易地循环遍历所有值,将数据作为表格数据输出到一个表中,如下所示:
<cfscript>
// output style for better view
writeOutput("<style>table,th,td{border:1px dotted gray;}</style>");
// output table body and header
writeOutput("<table><tbody>");
writeOutput("<tr><th>Column1</th><th>Column2</th><th>Column3</th></tr>");
for( row in myMatrix2DArray ){
//open new table row
writeOutput("<tr>");
for( column in row ){
writeOutput("<td>#column#</td>");
}
//close table row
writeOutput("</tr>");
}
writeOutput("</tbody></table>");
</cfscript>这种方法的最佳方法是,您可以轻松地访问矩阵数组的一个特定值,只需使用:myMatrix2DArray[row][colum]引用行索引和列索引,如下所示:
<cfscript>
writeOutput("<div>Value for Row=2 and Column=3: <strong>#myMatrix2DArray[2][3]#</strong></div>");
writeOutput("<div>Value for Row=3 and Column=1: <strong>#myMatrix2DArray[3][1]#</strong></div>");
</cfscript>https://stackoverflow.com/questions/70541331
复制相似问题