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');
});
});

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');
});
});
添加回答
舉報