我正在尝试让我的脚本组合一个多维数组。这通常不应该是一个问题,但由于某种原因,这里一切都失败了,我不知道为什么。
function getProducts(products){
var allProducts = new Array();
for(var p in products) if(products[p]){
var groupName = products[p].otherGroupName;
var code = (products[p].code.split("."))[0];
if( !(products[p].commonName.length==0 && groupName=="") ){
if(groupName=="") {
groupName="Custom Admin Products";
}
if(!(groupName in allProducts)) {
allProducts[groupName] = new Array();
}
var np = {};
np.commonName = products[p].commonName;
np.code = code;
allProducts[groupName][np.code] = np;
}
}
console.log(allProducts);
}
products
的参数是一个对象。您还会在倒数第二行看到,我正在尝试记录数组,它应该已填充,但它在日志中显示 '[]'
。如果我记录 allProducts[groupName][np.code]
它会给我一个结构。所以我完全迷路了。
最佳答案
如果您想要像 PHP 等其他动态语言一样的“关联数组”,则数组对象应该具有数字索引,您应该使用对象。尝试使用 a = {}
,而不是将其声明为 new Array()
或相同的 a = []
。这将允许您使用“命名”索引。
此外,使用 .map()
似乎可以根据您的需要进行调整,这可以稍微提高代码的易读性。
有关更多背景信息,请参阅数组的 MDN 文档:
Some people think that you shouldn't use an array as an associative array. In any case, you can use plain objects instead, although doing so comes with its own caveats.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Description
关于javascript - 即使正在设置索引,数组仍显示为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464022/