You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue按first_name排序数组报this.todos.player_name.sort不是函数如何解决

问题原因

  • 直接调用Array.sort()无法对对象数组按指定字段排序:默认的sort()方法会将数组元素转为UTF-16字符串比较大小,你数组内的元素都是对象,转字符串后均为[object Object],自然无法按first_name排序。
  • 出现sort is not a function报错的核心原因是调用sort方法的目标不是数组:检查你的业务代码中是否有其他地方对this.todos.player_name进行了赋值操作,导致它被改为非数组类型(比如对象、字符串、undefined等)。

修复方案

将你的alertName方法替换为以下代码即可:

alertName: function(){
  // 先做类型校验,避免非数组场景报错
  if (!Array.isArray(this.todos.player_name)) return
  // 传入自定义比较函数,按first_name排序
  this.todos.player_name.sort((a, b) => {
    return a.first_name.localeCompare(b.first_name)
  })
  console.log(this.todos.player_name)
}

补充说明

  • 字符串比较使用localeCompare方法可以完美适配中英文、特殊字符的排序场景,比直接大小比较兼容性更好。
  • Vue2对数组的sort、push、splice等变异方法做了响应式劫持,直接调用修改原数组可以正常触发视图更新,不需要额外处理。

内容的提问来源于stack exchange,提问作者Yahoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:51:00