亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從包含關鍵字的列表中刪除條目 - 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條經驗 獲得超14個贊

如果 中的索引為負數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 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號