Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - Delete list command deletes all elements from the array

I'm trying to make a series of commands to make a list: !addlist, !viewlist, and !deletelist.

For the list I am using a JSON file:

{
  "listContent": []
}

And for the command file for the !deletelist command:

const Discord = require('discord.js')
const list = require('../list.json')
const fs = require('fs')

module.exports = {
    name: 'deletelist',
    execute(message, args) {
        var rawContent = fs.readFileSync('list.json')
        var content = JSON.parse(rawContent)
        var contentList = content.listContent
        var deletedOne = contentList[parseInt(args[0])]

        content.listContent.splice(deletedOne)

        message.channel.send(`${deletedOne} has been deleted!`)

        fs.writeFile('list.json', JSON.stringify(content), function writeJSON(err) {
            if (err) return console.log(err);
        })
    }
}

My problem is that instead of deleting the specified element in the array, it deletes all of them. I don't get an error or anything, my list just becomes empty.

question from:https://stackoverflow.com/questions/65941138/delete-list-command-deletes-all-elements-from-the-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured it out.

I need to:

  1. Change the .splice(deletedOne) to .splice(parseInt(args[0])) (Thanks Lux)
  2. Add a number of elements to replace, so I needed it to be .splice(parseInt(args[0]), 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...