javascript - 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();
解决方案
推荐阅读
- kubernetes - 自动驾驶模式下 GKE 上的 Istio
- javascript - 将 Base64 格式的照片作为 BLOB 添加到 FormData
- node.js - 如何使用 react-admin 中的参考文件在猫鼬中启用排序和过滤
- amazon-web-services - 在 ECS (AWS) 中更新服务后 CodeDeploy 不会自动运行
- html - 如何使用服务器将我的文件存储在我的网站中?
- javascript - AWS Cloudfront Lambda@Edge 奇怪的异步/回调用法
- java - 有没有办法定义 cdi 销毁实例的顺序?
- jquery-validate - 根据下拉选择更改文本框上的正则表达式验证
- javascript - 如何使用 vanilla JavaScript 检测和显示 WiFi 信号强度
- javascript - 获取两个div的实时位置并更新连接线