我的客户想要在每个合适的列中列出每个项目的列表,并列出其所属类别的名称.
<cfscript>
arr = ArrayNew(1);
arr[1] = '';
arr[2] = 'category B';
stc["Item One"] = arr;
arr[1] = 'category A';
arr[2] = '';
stc["Item Two"] = arr;
arr[1] = 'category A';
arr[2] = 'category B';
stc["Item Three"] = arr;
writedump(stc);
for (element in stc) {
WriteOutput(element & '<br>');
// The next line produces:
// Object of type class java.lang.String cannot be used as an array
for (i=1; i<=ArrayLen(element); i+=1) {
}
}
</cfscript>
Run Code Online (Sandbox Code Playgroud)
问:如何访问每个元素内的数组?
在您的示例中,您使用for ... in循环来遍历结构的键,而不是值.这可能有点令人困惑,因为与数组相同的语法将遍历元素.
在您的代码中,您已将键字符串放入element,而不是数组.这Object of type class java.lang.String cannot be used as an array就是产生错误的原因.
正如RRK所回答的那样,要访问结构中的值,您需要使用语法struct[keyOfItem].
//Loop keys in the struct
for (key in stc) {
writeOutput(key & '<br>');
//Loop items in the array
for(element in stc[key]){
writeOutput(element & '<br>');
}
}
Run Code Online (Sandbox Code Playgroud)