在JS中,你能依靠比较字符串与">"和"<"运算符吗?

Cum*_*bus 13 javascript

我正在构建一个抽象表,表中的每一列都可以包含所有数字或所有字符串.通过单击列标题可以对每列进行排序.

目前我正在使用JS本机排序并传递compareFunction:

const rows = [
  {name: 'Adam', age: 27, rank: 3},
  {name: 'Zeek', age: 31, rank: 1},
  {name: 'Nancy', age: 45, rank: 4},
  {name: 'Gramps', age: 102, rank: 2},
]

const compareFn = (x, y) => {
  const sortDirValue = this.state.sortDirection === 'DESC' ? 1 : -1
  if (x[this.state.sortBy] === y[this.state.sortBy]) return 0
  return x[this.state.sortBy] < y[this.state.sortBy] ? sortDirValue : -sortDirValue
}

this.state = {
  sortBy: 'name',
  sortDirection: 'ASC'
}
rows.sort(compareFn)
console.log('---- Sorted by alphabetical name ----')
console.log(rows)

this.state = {
  sortBy: 'age',
  sortDirection: 'DESC'
}
rows.sort(compareFn)
console.log('---- Sorted by descending age ----')
console.log(rows)
Run Code Online (Sandbox Code Playgroud)

在我迄今为止尝试的所有测试案例中,这似乎都有效.但是,我知道JS可以通过排序来挑剔,比如开箱即用sort()将按字母顺序排序数字数组.

我可以依靠上述方法对数字和字符串进行一致的正确排序吗?如果没有,那么这种方式无法正确排序的数据示例是什么.

Cum*_*bus 7

,人们不能依赖于>/ <运算符的字母排序.这种方式无法正确排序数据的最突出的例子是大写和小写字符的混合.

其他答案的有效之处在于使用localeCompare是比较字符串的方法.但是,我发现字符串和数字的数字和混合也可以通过这种方式进行有效比较.

x.localeCompare(y, 'kn', { numeric: true })
Run Code Online (Sandbox Code Playgroud)

通过利用localeCompare提供的数字选项,我能够实现更强大的排序,同时还避免了需要分支条件逻辑来处理每个stringnumber案例.

const rows = [
  {name: 'Adam', age: 27, rank: 3, thing: 19},
  {name: 'Zeek', age: 31, rank: 1, thing: 'wut dis'},
  {name: 'Nancy', age: 45, rank: 4, thing: '$dolla'},
  {name: 'Gramps', age: 102, rank: 2, thing: 2},
]

const compareFn = (x, y) => {
  const xData = x[this.state.sortBy].toString()
  const yData = y[this.state.sortBy].toString()
  if (this.state.sortDirection !== 'DESC') {
    return xData.localeCompare(yData, 'kn', { numeric: true })
  } else {
    return yData.localeCompare(xData, 'kn', { numeric: true })
  }
}

this.state = {
  sortBy: 'name',
  sortDirection: 'ASC'
}
rows.sort(compareFn)
console.log('---- Sorted by alphabetical name ----')
console.log(rows)

this.state = {
  sortBy: 'age',
  sortDirection: 'DESC'
}
rows.sort(compareFn)
console.log('---- Sorted by descending age ----')
console.log(rows)

this.state = {
  sortBy: 'thing',
  sortDirection: 'ASC'
}
rows.sort(compareFn)
console.log('---- Sorted by ascending thing ----')
console.log(rows)
Run Code Online (Sandbox Code Playgroud)