首页 > 解决方案 > Javascript .sort() 返回的真/假与预期不同

问题描述

在下面的代码示例中,我将“item”作为石头或铜传入。这意味着获取所有库存项目,按字母顺序排序,并再次附加覆盖旧的。我的问题是第一次,排序函数将'a'评估为铜,'b'评估为石头,并返回-1(错误,正确吗?)。然后,如果值为 0,则它会删除该元素。当添加那个元素时,它有'a'作为石头和'b'作为铜,再次返回-1,然后先用石头排序。我对如何/为什么感到困惑,并且认为我已经盯着这个太久了,以至于我看不出有什么问题。任何帮助将不胜感激!最小的可重现示例:

var ConsoleButtons = {
    initialize: function() {
    cbOne.addEventListener("click", function() { ConsoleButtons.cbOneClick(); });
    cbOneClick: function() {
        PlayerInventory.addToBag(stone, 1);
        PlayerInventory.addToBag(copper, 1);
    }  
    }
}
var PlayerInventory = {
    initialize: function() {
    plyrInv = document.createElement('div');
    plyrInv.setAttribute('id', "playerInv");
    wrapper.append(plyrInv);
    },
    addToBag: function(item, qty) {
        item.quantity += qty;
        console.log(item.name + item.quantity);
        PlayerInventory.checkInv(item);
    },
    removeFromBag: function(item, qty) {
        item.quantity -= qty;
        if (item.quantity < 0) {
            item.quantity = 0;
        }
        console.log(item.name + item.quantity);
        PlayerInventory.checkInv(item);
    },
    createRescDisp: function(item) {
        if (item.para === undefined || item.para === null) {
            item.para = document.createElement('p');
            item.para.setAttribute('class', 'inventoryItem');
            item.para.setAttribute('id', item);
            item.para.innerHTML = item.name + ": " + item.quantity;
            invParent = document.getElementById('playerInv');
            invParent.appendChild(item.para);
            //Sort: compare a to b.
            //If a is larger than b, return true. else, false.
            invParArr = Array.from(invParent.children);
            //invParArr.sort((a,b) => a.getAttribute('id') > b.getAttribute('id') ? 1 : -1);
            for (i = 0; i < invParArr.length; i++) {
                invParent.append(invParArr[i]);
            }
}
PlayerInventory.initialize();
ConsoleButtons.initialize();

标签: javascriptarrayssorting

解决方案


推荐阅读