首页 > 解决方案 > 如何编辑从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

取决于玩家首先收集的水果。

标签: javascriptsqlactionscript-3

解决方案


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


推荐阅读