为了账号安全,请及时绑定邮箱和手机立即绑定

从包含关键字的列表中删除条目 - nodeJS

从包含关键字的列表中删除条目 - nodeJS

拉丁的传说 2023-07-06 16:51:06
所以我有这段代码来读取 txt 文件并检查搜索关键字的条目并删除此行。效果很好,但是如果找不到关键字,它不会停止,而是继续并删除文件的最后一行。我不希望它这样做,但如果在列表中找不到关键字则停止。const fs = require ('fs');fs.readFile('./test/test2.txt', 'utf-8', function(err, data) {    if (err) throw error;    let dataArray = data.split('\n');     const searchKeyword = 'UserJerome';    let lastIndex = -1;     for (let index=0; index<dataArray.length; index++) {        if (dataArray[index].includes(searchKeyword)) {            lastIndex = index;             break;         }    }    dataArray.splice(lastIndex, 1);     const updatedData = dataArray.join('\n');    fs.writeFile('./test/test2.txt', updatedData, (err) => {        if (err) throw err;        console.log ('Successfully updated the file data');    });}); 
查看完整描述

2 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

如果 中的索引为负数splice,则将从末尾开始那么多元素。因此x.splice(-1, 1)从末尾开始一个元素x并删除一个元素。


const fs = require ('fs');


fs.readFile('./test/test2.txt', 'utf-8', function(err, data) {

    if (err) throw error;


    let dataArray = data.split('\n'); 

    const searchKeyword = 'UserJerome';

    let lastIndex = -1; 


    for (let index=0; index<dataArray.length; index++) {

        if (dataArray[index].includes(searchKeyword)) {

            lastIndex = index; 

            break; 

        }

    }


    if (lastIndex !== -1) { // <-----------------------------------

       dataArray.splice(lastIndex, 1); 

    }

    const updatedData = dataArray.join('\n');

    fs.writeFile('./test/test2.txt', updatedData, (err) => {

        if (err) throw err;

        console.log ('Successfully updated the file data');

    });


}); 


查看完整回答
反对 回复 2023-07-06
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您可以只使用向后for loop(这样我们在循环时不会弄乱数组的顺序)并执行slice其中的方法。


const fs = require ('fs');


fs.readFile('./test/test2.txt', 'utf-8', function(err, data) {

    if (err) throw error;


    let dataArray = data.split('\n'); 

    const searchKeyword = 'UserJerome';

    

    for (let index = dataArray.length - 1; index >= 0; index--) {

        if (dataArray[index].includes(searchKeyword)) {

          dataArray.splice(index, 1);

        }

    }


    const updatedData = dataArray.join('\n');

    fs.writeFile('./test/test2.txt', updatedData, (err) => {

        if (err) throw err;

        console.log ('Successfully updated the file data');

    });

});


查看完整回答
反对 回复 2023-07-06
  • 2 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信