简体   繁体   English

如何在 Google Apps Scripts 字典中使用数组作为键,并在遍历字典时保持其数组结构

[英]How do I use an array as a key in a Google Apps Scripts dictionary and have it maintain its array structure while I iterate over the dictionary

Why do the square brackets of the array get taken away when I use the array as a key?当我使用数组作为键时,为什么数组的方括号会被拿走? Looking at this function and the output vs expected output, how do I make sure the key is actually an array and that I can index it as such?查看此函数和输出与预期输出,我如何确保键实际上是一个数组并且我可以这样索引它?

function functionName() {
  d = {};
  a = [3, 3];
  d[a] = 100;
  Logger.log(d);
  //output: {3,3=100.0}
  //expected output: {[3,3]=100.0}
  for (var key in d){
    Logger.log(key);
    //output: 3,3
    //expected output: [3, 3]
    Logger.log(d[key]);
    //output: 100.0

    //I would like to be able to say
    //index1 = key[0];
    //index2 = key[1];
    //where index1 and index2 will evaluate to 3
    //but this throws an error
  }

}

Thanks谢谢

Because Objects only allow strings as keys.因为对象只允许字符串作为键。 Use Map instead:改用地图

 function functionName() { d = new Map(); a = [3, 3]; d.set(a,100); console.log([...d]);//expected output: {[3,3]=100.0} d.forEach((value, key)=>console.info({key,value})) } functionName();

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

相关问题 如何使用 vanilla javascript 遍历 json 文件中的子数组字典? - How do I iterate over a sub array dictionary in json file using vanilla javascript? 在Google Apps脚本中,如何让单个函数遍历跟踪多个不同变量对的数据结构? - In Google Apps Script, how can I have a single function iterate over a data structure that keeps track of many different pairs of variables? 如何遍历数组值的字典以呈现组件? ReactJS - How to iterate over dictionary of array values to render components? ReactJS 迭代数组时如何使用setTimeout或setInterval? - How do I use setTimeout or setInterval while iterating over an array? 如何遍历此数组结构 - How to iterate over this array structure 我如何一次又一次地遍历数组,同时将其每个值分配给DOM中的所有svg - How can I iterate through an array over and over again while assigning each of its values to all the svgs in my DOM 我需要遍历JSON数组-不确定如何执行-已搜索但仍然无法获得线索 - I need to iterate over a JSON array - not sure how to do it - have searched but still can't get a clue 如何使用 Javascript 在数组元素上迭代两次? - How can I use Javascript to iterate twice over an array element? 如何使用映射函数无限迭代数组? - How do I iterate over an array with a map function, infinitely? 如何遍历json结果并添加到数组? - How do I iterate over json result and add to array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM