javascript - 如果键是数组,如何找到键的值?
问题描述
我正在尝试将字典作为返回颜色的坐标。
我用键作为数组制作了一个字典,比如[0, 1]
. 但是,我无法通过提供密钥来获得价值。
dict = {
key: [0, 1],
value: "red"
}
dict[[0, 1]]
我希望dict[[0, 1]]
给值“红色”,但它只是说“未定义”。
解决方案
对于使用数组作为键,您可以使用 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);
推荐阅读
- xcode - SwiftUI - 按钮操作未激活
- lwc - 如何在闪电控制台主选项卡而不是 LWC 中的子选项卡中打开自定义记录?
- node.js - Firebase 部署错误:TS2694:命名空间“admin”没有导出的成员“appCheck”
- awk - awk 通过匹配模式重定向到不同的文件并在重定向之前执行替换
- c# - 使用 list.Count() 设置 for 循环错误的限制数量
- asp.net-core - ASP.NET Core 5:输出文件夹缺少某些程序集
- java - 函数返回值中的java帮助
- sharepoint - 通过 Internet 访问共享点站点
- asp.net-core - Ocelot 网关不想申请微服务路由
- php - 重建 Github 仓库树结构