gpt4 book ai didi

javascript - 如果键是数组,如何找到键的值?

转载 作者:行者123 更新时间:2023-11-28 14:20:06 27 4
gpt4 key购买 nike

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

我制作了一个字典,其中的键作为数组,例如 [0, 1] 。但是,我无法通过提供 key 来获取值。

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

dict[[0, 1]]

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

最佳答案

要使用数组作为键,您可以使用 Map以对数组的对象引用作为键。

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

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);

关于javascript - 如果键是数组,如何找到键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55550924/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com