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

所以我有这段代码来读取 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');

    });


}); 


拉丁的传说
浏览 138回答 2
2回答

翻翻过去那场雪

如果 中的索引为负数splice,则将从末尾开始那么多元素。因此x.splice(-1, 1)从末尾开始一个元素x并删除一个元素。const fs = require ('fs');fs.readFile('./test/test2.txt', 'utf-8', function(err, data) {&nbsp; &nbsp; if (err) throw error;&nbsp; &nbsp; let dataArray = data.split('\n');&nbsp;&nbsp; &nbsp; const searchKeyword = 'UserJerome';&nbsp; &nbsp; let lastIndex = -1;&nbsp;&nbsp; &nbsp; for (let index=0; index<dataArray.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; if (dataArray[index].includes(searchKeyword)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lastIndex = index;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (lastIndex !== -1) { // <-----------------------------------&nbsp; &nbsp; &nbsp; &nbsp;dataArray.splice(lastIndex, 1);&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; const updatedData = dataArray.join('\n');&nbsp; &nbsp; fs.writeFile('./test/test2.txt', updatedData, (err) => {&nbsp; &nbsp; &nbsp; &nbsp; if (err) throw err;&nbsp; &nbsp; &nbsp; &nbsp; console.log ('Successfully updated the file data');&nbsp; &nbsp; });});&nbsp;

慕莱坞森

您可以只使用向后for loop(这样我们在循环时不会弄乱数组的顺序)并执行slice其中的方法。const fs = require ('fs');fs.readFile('./test/test2.txt', 'utf-8', function(err, data) {&nbsp; &nbsp; if (err) throw error;&nbsp; &nbsp; let dataArray = data.split('\n');&nbsp;&nbsp; &nbsp; const searchKeyword = 'UserJerome';&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for (let index = dataArray.length - 1; index >= 0; index--) {&nbsp; &nbsp; &nbsp; &nbsp; if (dataArray[index].includes(searchKeyword)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataArray.splice(index, 1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; const updatedData = dataArray.join('\n');&nbsp; &nbsp; fs.writeFile('./test/test2.txt', updatedData, (err) => {&nbsp; &nbsp; &nbsp; &nbsp; if (err) throw err;&nbsp; &nbsp; &nbsp; &nbsp; console.log ('Successfully updated the file data');&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript