gpt4 book ai didi

javascript - 对对象的代理数组进行排序,localeCompare 不是函数

转载 作者:行者123 更新时间:2023-12-05 00:31:31 27 4
gpt4 key购买 nike

尝试使用 ES6 arrayObj.sort(a,b) => a.property.localeCompare(b.property)语法但出现错误:

TypeError: a.property.localeCompare is not a function.


我在想 localeCompare不在范围内但不明白如何将其绑定(bind)到排序范围,可能是因为数据存储在代理中?我也在 VueJS 3 中工作,但认为这与这个问题无关。
myData = 
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}}
[[Handler]]: Object
[[Target]]: Array(5)
0: {itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1, …}
1: {itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0, …}
2: {itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0, …}
3: {itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0, …}
4: {itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1, …}

myData.sort((a, b) => a.itemIndex.localeCompare(b.itemIndex))

最佳答案

localeComparemethod of String , 但是 a.itemIndexNumber ,因此该方法在该属性上不可用。
itemIndex 排序, 对两个 Number 使用减法年代:

const myData = [
{itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1 },
{itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0},
{itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0},
{itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0},
{itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1},
]

// sort by itemIndex in ascending order
myData.sort((a,b) => a.itemIndex - b.itemIndex)

console.log(myData)

itemFmtName 排序, 使用 localeCompare关于两个 String年代:

const myData = [
{itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1 },
{itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0},
{itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0},
{itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0},
{itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1},
]

// sort by itemFmtName in alphabetical order
myData.sort((a,b) => a.itemFmtName.localeCompare(b.itemFmtName))

console.log(myData)

关于javascript - 对对象的代理数组进行排序,localeCompare 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69235003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com