数组元素值无故改变

Array element values changing without reason

我正在尝试为我的服务器制作一个 discord 机器人(一个货币机器人)并且我正在尝试实现一个交易系统,但是我用于交易项目的数组中有一些项目的值是随机变化的。我没有在其他任何地方更改数组值,但值仍在变化。有谁知道为什么?代码像这样解析输入:3apple,1stick 1axe .

trade.ts

youend = [];
themend = [];
var temp: Item | undefined;
for (var i = 0; i < you.length; i++) {
  const item = you[i];
  for (let i = 0; i < ITEMS.length; i++) {
    const item2 = ITEMS[i];
    temp = undefined;
    if (
      reAll(
        item
          .slice(/[a-z]/i.exec(reAll(item.toLowerCase(), "_", " "))?.index)
          .toLowerCase(),
        "_",
        " "
      ) === item2.name.toLowerCase()
    ) {
      let temp = item2;
      //@ts-ignore
      temp.amount = parseInt(
        item.slice(
          0,
          /[a-z]/i.exec(reAll(item.toLowerCase(), "_", " "))?.index + 1
        )
      );
      youend.push(temp);
      console.log(JSON.stringify(temp), youend, themend);
    }
  }
}
temp = undefined;
for (var i = 0; i < them.length; i++) {
  const item = them[i];
  for (let i = 0; i < ITEMS.length; i++) {
    const item2 = ITEMS[i];
    temp = undefined;
    if (
      reAll(
        item
          .slice(/[a-z]/i.exec(reAll(item.toLowerCase(), "_", " "))?.index)
          .toLowerCase(),
        "_",
        " "
      ) === item2.name.toLowerCase()
    ) {
      let temp = item2;
      //@ts-ignore
      temp.amount = parseInt(
        item.slice(
          0,
          /[a-z]/i.exec(reAll(item.toLowerCase(), "_", " "))?.index + 1
        )
      );
      themend.push(temp);
      console.log(JSON.stringify(temp), youend, themend);
    }
  }
}

项目class

export class Item {
    name: string
    icon: string
    sell: number
    durability: number
    amount: number
    constructor(name: string, icon: string, sell: number, durability: number, amount: number) {
        this.name = name
        this.icon = icon
        this.sell = sell
        this.durability = durability
        this.amount = amount
    }
}

我不确定这是否是解决方案,但看起来您在 for 循环中使用了两个 i 变量。


在你的两个 for 循环中,你定义了两个 i 变量,使用 varlet

for (var i = 0; i < arr.length; i++) {
  for (let i = 0; i < arrTwo.length; i++) {
    
  }
}

这应该无法正常工作,因此一个很好的解决方法是将它们都更改为不同的变量名。

for (var i = 0; i < arr.length; i++) {
  for (let j = 0; i < arrTwo.length; i++) {
    
  }
}

此外,您不应同时使用 varlet。你应该坚持一个。

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; i < arrTwo.length; i++) {
    
  }
}

这些更改可能会修复您的代码。


总之,解决方案可能是更改变量名称。