【问题标题】:Why isn't my function sorting object properties correctly?为什么我的函数不能正确排序对象属性?
【发布时间】:2020-03-11 21:12:39
【问题描述】:

我正在制作一个带有可排序列的反应表。当我对年龄行进行排序时,结果排序不正确。我回去检查以确保我正确排序并在数据中添加了一些重复数字。我还检查了数据中的空白或错误​​。我还尝试确保它们是数字而不是字符串。任何“年龄”属性似乎都没有任何问题。那么为什么排序认为 25 高于 32?

这里是代码(我去掉了重复的其他属性,用...注释,除了扩展运算符,当然是扩展运算符):

function PeopleList({participants}){
    const [reverse, setReverse] = useToggle(true);
    let [sortType, setSort] = useState('default')

    let reverseFunction = (arr) => {
        if(reverse){
            return arr.reverse()
        } else {
            return arr
        }
    }

let sortRows = {
...
        age: {
            class: 'age',
            fn: (a, b) => a-b
        },
        default: {
            class: 'default',
            fn: (a, b)=>a
        }
     }
return (
      <table>
            <thead>
                <tr>
...
                <td><Button onClick={()=>{setSort('age'); setReverse()}}>
...
                </tr>
            </thead>
            <tbody>
{reverseFunction([...list].sort(sortRows[sortType].fn)).map(person=>{
            return <tr>
...
                    <td>{person.age}</td>
...
                   </tr>
)}
)}

这是结果排序的屏幕截图:

【问题讨论】:

  • tbody中sortType的值是多少?
  • 该按钮将其设置为年龄,但它以默认方式开始。问题是我正在对对象而不是属性进行排序。
  • 输入的数字是字符串而不是整数?

标签: javascript arrays reactjs sorting object


【解决方案1】:

在我即将提交问题时注意到了错误。由于我仔细编辑了这个问题,我想我会提交它以防万一它对任何忽略相同错误的人有用。

我正在对对象进行排序,而不是对对象属性进行排序。要按年龄正确排序,应比较参数的年龄属性。

       age: {
            class: 'age',
            fn: (a, b) => a.age-b.age //Remember the property
        },

【讨论】:

  • 我可以想象这是一个不必要的复杂错误示例,如果发现它比任何东西更容易导致臃肿,我愿意将其删除。
猜你喜欢
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多