wqy
2020-03-31 12:30:21
3157

1 安装依赖

npm install locutus 或 cnpm install locutus

 

2 引入函数

这里本来是要直接引入使用的,但是测试了引入一直无法成功,所以直接把依赖里面的函数拿了出来,直接用。

 

这里要注意 函数里面有几个包引入,要根据实际项目包位置更换地址

 

export function ksort(inputArr, sortFlags) {
  const i18nlgd = require('locutus/php/i18n/i18n_loc_get_default')
  const strnatcmp = require('locutus/php/strings/strnatcmp')
  const tmpArr = {}
  const keys = []
  let sorter
  let i
  let k
  let sortByReference = false
  let populateArr = {}
  const $global = (typeof window !== 'undefined' ? window : global)
  $global.$locutus = $global.$locutus || {}
  const $locutus = $global.$locutus
  $locutus.php = $locutus.php || {}
  $locutus.php.locales = $locutus.php.locales || {}
  switch (sortFlags) {
    case 'SORT_STRING':
      // compare items as strings
      sorter = function(a, b) {
        return strnatcmp(b, a)
      }
      break
    case 'SORT_LOCALE_STRING':
      // compare items as strings, based on the current locale
      // (set with i18n_loc_set_default() as of PHP6)
      var loc = i18nlgd()
      sorter = $locutus.locales[loc].sorting
      break
    case 'SORT_NUMERIC':
      // compare items numerically
      sorter = function(a, b) {
        return ((a + 0) - (b + 0))
      }
      break
    default:
      // case 'SORT_REGULAR': // compare items normally (don't change types)
      sorter = function(a, b) {
        const aFloat = parseFloat(a)
        const bFloat = parseFloat(b)
        const aNumeric = aFloat + '' === a
        const bNumeric = bFloat + '' === b
        if (aNumeric && bNumeric) {
          return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0
        } else if (aNumeric && !bNumeric) {
          return 1
        } else if (!aNumeric && bNumeric) {
          return -1
        }
        return a > b ? 1 : a < b ? -1 : 0
      }
      break
  }
  // Make a list of key names
  for (k in inputArr) {
    if (inputArr.hasOwnProperty(k)) {
      keys.push(k)
    }
  }
  keys.sort(sorter)
  const iniVal = (typeof require !== 'undefined' ? require('locutus/php/info/ini_get')('locutus.sortByReference') : undefined) || 'on'
  sortByReference = iniVal === 'on'
  populateArr = sortByReference ? inputArr : populateArr
  // Rebuild array with sorted key names
  for (i = 0; i < keys.length; i++) {
    k = keys[i]
    tmpArr[k] = inputArr[k]
    if (sortByReference) {
      delete inputArr[k]
    }
  }
  for (i in tmpArr) {
    if (tmpArr.hasOwnProperty(i)) {
      populateArr[i] = tmpArr[i]
    }
  }
  return sortByReference || populateArr
}

 

示例

    var test =
 {
token: 'a21c6ce5ddacea3893f597c15e0d21565d8e66e419312ee32d0fa904d16f0790', 
limit: 10, 
timestamp: 1612428265, 
page: 1 
}
    ksort(test)
    console.log(test)

     // 排序后的结果 
{ limit: 10, 
page: 1, 
timestamp: 1612428265, 
token: 'a21c6ce5ddacea3893f597c15e0d21565d8e66e419312ee32d0fa904d16f0790'
 }

 

这里注意 ksort() 函数返回的结果是 true 

 

 

访问官网