首页 > 解决方案 > 如果键是数组,如何找到键的值?

问题描述

我正在尝试将字典作为返回颜色的坐标。

我用键作为数组制作了一个字典,比如[0, 1]. 但是,我无法通过提供密钥来获得价值。

dict = {
  key:   [0, 1],
  value: "red"
}

dict[[0, 1]]

我希望dict[[0, 1]]给值“红色”,但它只是说“未定义”。

标签: javascript

解决方案


对于使用数组作为键,您可以使用 aMap和对 tha 数组的对象引用作为键。

这种方法不适用于相似但不相等的数组。

var map = new Map,
    key = [0, 1],
    value = 'red';

map.set(key, value);

console.log(map.get(key));    // red
console.log(map.get([0, 1])); // undefined

要获取一组坐标,您可以采用嵌套方法。

function setValue(hash, [x, y], value) {
    hash[x] = hash[x] || {};
    hash[x][y] = value;
}

function getValue(hash, keys) {
    return keys.reduce((o, key) => (o || {})[key], hash);
}

var hash = {},
    key = [0, 1],
    value = 'red';

setValue(hash, key, value);

console.log(getValue(hash, key));
console.log(hash);

或者使用值分隔符的联合方法。

var hash = {},
    key = [0, 1].join('|'),
    value = 'red';

hash[key] = value;

console.log(hash[key]);
console.log(hash);


推荐阅读