如何在字典的末尾附加键值对? [英] How to append key value pairs at the end of the dictionary?

查看:253
本文介绍了如何在字典的末尾附加键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为每次单击分配0,每次双击分配1,并在地图中记录单击和位置。但是,即使我没有尝试对它们进行排序,键也按升序排序。有没有办法在确保所有点击注册时添加1或0作为最后值的位置键?我甚至尝试使用 String(i)将密钥转换为字符串。

I'm trying to assign 0 to every single click and 1 to every double click and have a log of the click and the position in a map. However, the keys are all sorted in ascending order even though I did not try to sort them. Is there a way to add the position key with the 1 or 0 as the value at the end while making sure all clicks register? I even tried converting the key to a string using String(i).

这是完整我正在处理的项目的代码: Codesandbox

Here is the full code for the project I'm working on: Codesandbox

var lastClicked;
var map = {};

var grid = clickableGrid(20, 30, function(el, row, col, i, isDoubleClick) {

  if (!isDoubleClick && !el.className) {
    el.className = "clicked";
    map[String(i)] = 0;
  } else if (isDoubleClick && !el.className) {
    el.className = "niclicked";
    map[String(i)] = 1;
  }
  console.log(map);
});

document.body.appendChild(grid);

推荐答案

实际上,当你迭代它们时,访问普通对象中的键的顺序,不保证是按插入顺序。具体来说,(转换为数字时)的值是32位范围内的正整数,按数字顺序访问。

Indeed, the order of keys in plain objects are visited when you iterate them, is not guaranteed to be by insertion-order. Specifically, values that (when converted to number) are positive integers in the 32-bit range, get visited in numerical order.

数组是另一种选择,因为它们明确维护使用 push 时的插入顺序。缺点是他们不提供字典行为,你可以通过(原始)密钥找到条目。

Arrays are an alternative, as they clearly maintain insertion order when using push. The downside is that they do not offer the dictionary behaviour, whereby you can find the entry by (original) key.

如果你真的需要字典行为,在同时,插入顺序,然后地图可以是一个解决方案:

If you really need the dictionary behaviour and, at the same time, insertion-order, then Map can be a solution:

var lastClicked;
var map = new Map; // <---

var grid = clickableGrid(20, 30, function(el, row, col, i, isDoubleClick) {

  if (!isDoubleClick && !el.className) {
    el.className = "clicked";
    map.set(i, 0);
  } else if (isDoubleClick && !el.className) {
    el.className = "niclicked";
    map.set(i, 1);
  }
  map.forEach((value, key) => console.log(key, value)); //<-- insertion order!
});

document.body.appendChild(grid);

您可以使用: map.get(key)以恒定时间获取给定键的0/1值,就像使用普通对象一样。

You can use: map.get(key) to get the 0/1 value for a given key in constant time, like you would with a plain object.

这篇关于如何在字典的末尾附加键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆