在JavaScript中,我们可以使用以下代码实现camelCase属性的排名规则:
let orderByCamelCase = function (a, b) { const regex = /([A-Z])/g; const ax = [], bx = [];
a.replace(regex, function(m, $1) { return "-" + $1.toLowerCase(); }).split('-').forEach(function(v) { ax.push(isNaN(parseFloat(v)) ? v : parseFloat(v)) }); b.replace(regex, function(m, $1) { return "-" + $1.toLowerCase(); }).split('-').forEach(function(v) { bx.push(isNaN(parseFloat(v)) ? v : parseFloat(v)) });
for (let i = 0; ax && bx && i < ax.length && i < bx.length; i++) { if (ax[i] !== bx[i]) { return ax[i] < bx[i] ? -1 : 1; } }
return ax.length - bx.length; };
使用方法如下:
const array = ['camelCase1', 'camelCase11', 'camelCase2'];
console.log(array.sort(orderByCamelCase)); // ['camelCase1', 'camelCase2', 'camelCase11']