javascript - 如何编辑从s中的字符串转换而来的数组中的特定数字
问题描述
我有一个游戏(javascript),玩家可以在其中收集水果(苹果、香蕉、橙子)。Apples id 是 1,香蕉是 2,橙子是 3 所有这些信息都记录在 sql 中的一个字段中,该字段在 users 表中称为“fruits”。玩家最多只能收集3个同种水果
例如,如果玩家得到 3 个苹果、3 个香蕉、1 个橘子,则记录为:1:3 ,2:3 , 3:1
问题是如果他要收集另一个橙子,它必须像这样记录:1:3 ,2:3 , 3:2
但它的记录是这样的:
1:3 ,2:3 , 3:0 , 3:1
所以我通过 split(",") 将此字段从字符串转换为数组
但
返回示例我如何对其进行编码以在字段中搜索数字 3(这是橘子编号)并编辑其后的数字(如示例中的 1 到 2)并保存其余部分(苹果和香蕉的数量)
知果数在田间无特定排列
它可以像这样记录:
2:3 ,1:3 ,3:1
取决于玩家首先收集的水果。
解决方案
const IDs = { // Store ID references
"apple" : 1,
"banana": 2,
"orange": 3,
};
const max = 3;
const basket = {};
const collect = (item) => {
if (!IDs.hasOwnProperty(item)) return; // No such item
const id = IDs[item];
if (!basket[id]) basket[id] = 0; // Set to 0 if was not existent
if (basket[id] === max ) { // Throw an error if max
return alert(`You already have ${max} ${item}s`);
}
basket[id] += 1; // Increment if no alerts
};
collect("apple");
collect("banana");
collect("apple");
collect("apple");
collect("apple"); // Should give an error
console.log(basket); // Let's see what we have in the basket so far
推荐阅读
- java - 将变量从一种方法传递到另一种方法?
- react-native - 我正在使用 EXPO.IO 处理本机项目,今天它给出了错误 Unable to resolve module @babel
- php - 使用数据提供者时压倒性的 testdox 输出(具有大量数据集)
- html - 我正在尝试设置范围输入的拇指样式,但 webkit 不起作用
- c# - 如果 Employee 存在,则使用 ADO.net 返回员工角色
- php - 将 CakePHP 网站升级到 PHP 7
- c# - 将 AllowsTransparency 属性设置为 true 的 WPF 窗口
- azure - 将 100 台设备附加到 Azure IoT 中心并为每台设备创建一个 Azure 事件中心是个好主意
- javascript - 如何修复 dataTables 搜索框和分页位置问题?
- postgresql - PostgreSQL 中的 Index-Only 和 Bitmap Index Scan 有什么区别?