How to sort strings in JavaScript

后端 未结 12 2236
生来不讨喜
生来不讨喜 2020-11-22 13:20

I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    retur         


        
12条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 13:27

    In your operation in your initial question, you are performing the following operation:

    item1.attr - item2.attr
    

    So, assuming those are numbers (i.e. item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. The following should work:

    return parseInt(item1.attr) - parseInt(item2.attr);
    

    If they are alphaNumeric, then do use localCompare().

提交回复
热议问题