【问题标题】:A way to set property of array contents?一种设置数组内容属性的方法?
【发布时间】:2014-01-01 23:51:38
【问题描述】:

我有一个库存脚本,用于从数组中创建玩家库存读数。我需要设置一个 .amount 属性,但是当我尝试像这样设置它们时出现一些未定义的错误。我不能使用集合或哈希图。谁能告诉我我错过了什么?

我目前仅使用 NaN 来调试代码。

    //This is already defined as an array, just a shortcut.//
    var inv = state.history[0].variables.player.inventory;
    inv[i].amount = 0;

    //Do this for every item in the inventory.//
    for (var i = 0; i < inv.length; i++) {

        //If the inventory item is Apple should resolve to ...inventory.Apple.amount.//
        var q = inv[i].amount;

        //If we find a duplicate in the array, just count and keep going.//
        if (inv[i] == inv[i-1]){
            q = (q + 1);

        //If the item is the last one or unique, print the item on the inventory screen.//
        } else {
            q = (q + 1);
            alert(inv[i] + " " + q.NaN);
            new Wikifier(place, inv[i] + " " + q.NaN + "<br>");
        }
    }

【问题讨论】:

  • Java !== JavaScript :)
  • Java 之于 JavaScript 就像 Car 之于 Carpet

标签: javascript arrays properties undefined


【解决方案1】:

你试图在循环中定义它之前获取 i,把它放在后面:

//This is already defined as an array, just a shortcut.//
var inv = state.history[0].variables.player.inventory;

//Do this for every item in the inventory.//
for (var i = 0; i < inv.length; i++) {
    inv[i].amount = 0;

    //If the inventory item is Apple should resolve to ...inventory.Apple.amount.//
    var q = inv[i].amount;

    //If we find a duplicate in the array, just count and keep going.//
    if (inv[i] == inv[i-1]){
        q = (q + 1);

    //If the item is the last one or unique, print the item on the inventory screen.//
    } else {
        q = (q + 1);
        alert(inv[i] + " " + q.NaN);
        new Wikifier(place, inv[i] + " " + q.NaN + "<br>");
    }
}

【讨论】:

  • 对不起,应该这样问。我按照建议这样做了,但 inv[i].amount 仍然未定义。 imgur.com/ga0Ggvr
猜你喜欢
  • 1970-01-01
  • 2015-06-21
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多