【问题标题】:Define and sort array of array content in TypeScript and Node.js在 TypeScript 和 Node.js 中定义和排序数组内容数组
【发布时间】:2021-09-16 16:54:06
【问题描述】:

几周前刚接触 TypeScript,对 JavaScript 了解不多。

我正在尝试遍历指定目录中的所有文件,并将每个文件名(string)和更改时间(number)放入数组数组中,并按更改时间排序。

看起来像这样:[['natalie.jpg', 143], ['mike.jpg', 20], ['john.jpg', 176], ['Jackie.jpg', 6]]

问题一:不知道如何指定内部数组内容、字符串和数字。类型?界面?班级?元组?

问题2:不知道怎么按变化时间升序排序,所以数组变成:[['Jackie.jpg', 6], ['mike.jpg', 20], ['natalie.jpg', 143], ['john.jpg', 176]]

import fs from 'fs'

const dirPath = '/home/me/Desktop/'

type imageFileDesc = [string, number] // tuple

const imageFileArray = [imageFileDesc] // ERROR HERE!

function readImageFiles (dirPath: string) {
  try {
    const dirObjectNames = fs.readdirSync(dirPath)

    for (const dirObjectName of dirObjectNames) {
      const dirObject = fs.lstatSync(dirPath + '/' + dirObjectName)
      if (dirObject.isFile()) {
        imageFileArray.push([dirObjectName, dirObject.ctimeMs]) // ERROR HERE!
      }
    }

    imageFileArray.sort(function (a: number, b: number) {
      return b[1] - a[1] // ERROR HERE! Can we do something like b.ctime - a.ctime?
    })
  } catch (error) {
    console.error('Error in reading ' + dirPath)
  }
}

readImageFiles(dirPath)
console.log(imageFileArray)

【问题讨论】:

  • 你要找的类型是[ string, number ][]吗?
  • @bitomic:当我更改为 const imageFileArray = [ string, number ][] 时,它说,“ 'string/number' 仅指一种类型,但在这里用作值。 "
  • 您错误地使用了类型,我建议您查看typescriptlang.org/docs 的 Typescript 文档。他们比我在评论中解释得更好。 ??????

标签: node.js arrays typescript sorting


【解决方案1】:
import * as fs from 'fs'

// Read files in folder
const files = fs.readdirSync( './files' )
// This will store the file name and their modification time
const imageFileArray: [ string, Date ][] = []

for ( const file of files ) {
    // You can get a file's last modified time through fs.stat
    const stats = fs.statSync( `./files/${file}` )
    const modifiedTime = stats.mtime
    // Push a tuple containing the filename and the last modified time
    imageFileArray.push( [ file, modifiedTime ] )
}

// Sort from older to newer
const sorted = imageFileArray.sort( (a, b) => a[1].getTime() - b[1].getTime() )

console.log( sorted )

修改后的时间返回一个Date 对象。如果你想从新到旧排序,只需在sort函数中反转操作即可。

【讨论】:

    猜你喜欢
    • 2016-12-25
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2018-07-13
    • 2020-04-29
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多