我尝试下面的代码
var数据=

[{"name":"ramu","id":"719","gmail":"[email protected]","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"[email protected]","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"[email protected]","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);

错误:TypeError: s.name.sort is not a function

但是期望输出是["karthik","ramu", "ravi"]

最佳答案

尝试

var names = data.map(s=>s.name).sort(); //just move the sort out

演示

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "[email protected]",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "[email protected]",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "[email protected]",
    "ph": 2332233232,
    "points": 25
  }
];
//var names = data.map(s=>s.name).sort(); //just move the sort out
var names = data.map(s => s.name).sort((a, b) => a.localeCompare(b)); //used localeCompare instead of simple sort

console.log(names);

关于javascript - 排序值不在我在 map 上使用过的地方,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47328409/

10-12 07:00