首页 > 解决方案 > js中的这个排序功能是如何工作的?

问题描述

Next.js站点(此处为https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops)中,此示例:

import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(), 'posts')

export function getSortedPostsData() {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory)
  const allPostsData = fileNames.map(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '')

    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)

    // Combine the data with the id
    return {
      id,
      ...matterResult.data
    }
  })
  // Sort posts by date
  return allPostsData.sort(({ date: a }, { date: b }) => {
    if (a < b) {
      return 1
    } else if (a > b) {
      return -1
    } else {
      return 0
    }
  })
}

在此示例中,函数getSortedPostsData()的返回值是allPostsData的排序列表。帖子按日期排序。

我的问题是数组是如何排序的?

排序函数有两个参数{date:a} , {date:b}。它是否会自动将参数转换为日期对象,因为a.date 和 b.date是字符串

标签: javascriptnext.js

解决方案


这个答案显示了每种情况使用哪种排序算法。

不会自动将参数转换为日期。这必须事先完成。如果您说 Date a 和 b 是字符串,它们将根据提供给排序函数的回调按字典顺序进行比较。


推荐阅读