简体   繁体   English

简单的JavaScript二维数组

[英]Simple javascript 2d array

I've seen the big answer already, and everyone gives completely different answers with varying degrees of complexity. 我已经看到了一个很好的答案 ,并且每个人都给出了完全不同的答案,但复杂程度不同。

I'm trying to do this: 我正在尝试这样做:

var tempFiles=[];
tempFiles[req.query.tenant,file.name]=finalName;

I'm not sure if this is working or not. 我不确定这是否有效。

When I console.log(tempFiles) , I get 当我console.log(tempFiles) ,我得到

[ 'the value for file.name ': 'the value for final name' ]

Where did the value for req.query.tenant go? req.query.tenant的值在哪里? Is this a proper 2D array? 这是正确的2D阵列吗?

You can't use commas for this. 您不能为此使用逗号。 You have to have separate [ ] operators. 您必须有单独的[ ]运算符。

tempFiles[req.query.tenant][file.name]=finalName;

Perversely, your code was not a syntax error because the comma operator does exist. 相反,您的代码不是语法错误,因为确实存在逗号运算符。 The meaning of your version was: 您的版本的含义是:

  • evaluate the expression req.query.tenant 计算表达式req.query.tenant
  • throw that value away 丢掉那个价值
  • evaluate the expression file.name 计算表达式file.name
  • use that value as a property name to look up in the object referenced by "tempFiles" 使用该值作为属性名称,以在“ tempFiles”引用的对象中查找

Also, note that if you really just declared your array right before trying to make that assignment, it won't work. 另外,请注意,如果您真的只是在尝试进行赋值之前就声明了数组,那么它将不起作用。 You have to explicitly create the second dimension: 您必须显式创建第二个维度:

var tempFiles = [];
tempFiles[ req.query.tenant ] = [];
tempFiles[ req.query.tenant ] [ file.name ] = finalName;

Finally, if the property names involved — req.query.tenant and file.name — are strings, then you really shouldn't be using arrays anyway. 最后,如果所涉及的属性名称( req.query.tenantfile.name )是字符串,那么您实际上绝对不应该使用数组。 You should be creating plain objects: 您应该创建普通对象:

var tempFiles = {};
tempFiles[ req.query.tenant ] = {};
tempFiles[ req.query.tenant ] [ file.name ] = finalName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM