Python和JavaScript在字符串比较上的差异

Python和JavaScript在字符串比较上的差异

目录

推荐超级课程:

PythonJavaScript中,根据字符串末尾的字符进行排序时,Python中只需将字符串传递给sorted函数的key参数即可,而在JavaScriptsort方法中,如果不进行特殊处理,默认只能进行数值比较而不是字符串比较,因此需要稍作技巧。

Python

python 复制代码
def sort_by_last_char(arr):
    return sorted(arr, key=lambda x: x[-1])
arr = ['apple', 'banana', 'cherry', 'date']
sorted_arr = sort_by_last_char(arr)
print(sorted_arr)

!

  • sorted函数会根据指定的键(key)对数组进行排序。
  • 这里使用key=lambda x: x[-1],即以每个字符串的最后一个字符为基准进行排序。

JavaScript

使用localeCompare的方法

javascript 复制代码
const sortByLastCharLocaleCompare = arr => arr.sort((a, b) => a.charAt(a.length - 1).localeCompare(b.charAt(b.length - 1))); //也可以使用slice方法
const arr1 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr1 = sortByLastCharLocaleCompare(arr1);
console.log(sortedArr1);

!

  • sort方法会根据指定的比较函数对数组进行排序。
  • localeCompare会根据本地设置比较字符串,并据此进行排序。

使用charCodeAt的方法

javascript 复制代码
const sortByLastCharCharCodeAt = arr => arr.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
const arr2 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr2 = sortByLastCharCharCodeAt(arr2);
console.log(sortedArr2);

!

  • charCodeAt方法返回指定位置字符的Unicode编码。
  • sort方法内部,根据字符的Unicode值进行排序。
相关推荐
San301 天前
深入理解 JavaScript 事件机制:从事件流到事件委托
前端·javascript·ecmascript 6
best6661 天前
Javascript有哪些遍历数组的方法?哪些不支持中断?那些不支持异步遍历?
前端·javascript·面试
二川bro1 天前
特征工程完全手册:2025 Python实战技巧
开发语言·python
特级业务专家1 天前
Chrome DevTools 高级调试技巧:从入门到真香
前端·javascript·浏览器
爱学习的程序媛1 天前
【Web前端】Angular核心知识点梳理
前端·javascript·typescript·angular.js
小时前端1 天前
前端架构师视角:如何设计一个“站稳多端”的跨端体系?
前端·javascript·面试
p***h6431 天前
JavaScript图像处理开发
开发语言·javascript·图像处理
袅沫1 天前
Element-UI 番外表格组件
javascript·vue.js·ui
Hilaku1 天前
这 5 个冷门的 HTML 标签,能让你少写 100 行 JS
前端·javascript·html
杰克尼1 天前
vue_day06
前端·javascript·vue.js