메모 삭제
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 33개 중 15번째.
done 2는 노트 2를 제거해야 하며, 사람들은 done 뒤에 무엇이든 입력합니다.
인수는 문자열입니다. Number('2')는 2이고 Number('two')는 NaN입니다. Number.isInteger는 한 번의 검사로 NaN과 2.5를 거부합니다. 그런 다음 범위를 확인합니다. 목록은 1부터 세고 배열은 0부터 세므로, 노트 n은 인덱스 n - 1에 있으며 splice(i, 1)은 해당 항목을 제거합니다.
// node seat.js 4
const seat = Number(process.argv[2]);
if (!Number.isInteger(seat) || seat < 1 || seat > 30) {
console.error(`No seat ${process.argv[2]}`);
process.exit(1);
}
console.log(`Row ${Math.ceil(seat / 6)}`);챌린지
쉬움작업을 마치면 완료로 표시되고 목록에서 사라집니다. 번호로 메모를 삭제하는 done 명령을 추가하세요.
notes.js에done명령을 추가하세요.done뒤에 오는 단어는list에 표시된 메모 번호이므로, 메모 1은 첫 번째 메모입니다. 이 단어는 문자열로 전달됩니다.- 저장소에서 해당 메모를 삭제한 다음,
add가 메모를 저장하는 것과 같은 방식으로notes.json에 저장하세요. 메모 1은 배열의 인덱스 0에 있습니다. 삭제 코드는notes.js에 넣거나store.js의 메서드로 만들 수 있습니다. - 삭제한 메모의 내용 앞에
Done:을 붙여 출력하세요. 메모가Buy milk,Call Ada,Water the plants일 때node notes.js done 1을 실행하면 다음을 출력합니다:그러면Done: Buy milknotes.json에는Call Ada와Water the plants만 남습니다.done 3을 실행하면Water the plants가 삭제됩니다. - 단어가 메모 번호가 아니라면 아무것도 변경하지 마세요. stderr에
No note뒤에 해당 단어를 붙여 출력하고, 종료 코드 1로 종료하세요. 여기에는abc같은 단어,0,2.5같은 소수, 그리고 메모가 세 개일 때의9처럼 범위를 벗어난 숫자가 해당합니다.node notes.js done abc를 실행하면 빨간색으로 다음을 출력합니다:No note abc
직접 해보기: 메모와 번호를 확인하려면 $ node notes.js 뒤의 입력란에 list를 입력하세요. done 1을 입력한 다음 다시 list를 입력하세요. 첫 번째 메모가 사라지고 나머지 메모의 번호가 하나씩 올라갑니다. 그런 다음 done abc를 입력하세요. 빨간색으로 No note abc가 표시되고 종료 코드 1로 종료되며, list에는 이전과 같은 메모가 표시됩니다.
직접 해보기
// 메모 도구는 여기서 시작합니다.
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import store from './store.js';
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');
if (command === 'add') {
const n = store.add(text);
console.log(`Saved note ${n}.`);
} else if (command === 'list') {
const owner = process.env.NOTES_OWNER ?? 'you';
console.log(`Notes for ${owner}`);
if (store.notes.length === 0) {
console.log('No notes yet');
}
store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else if (command === 'where') {
const file = path.join(process.cwd(), 'notes.json');
console.log(file);
console.log(path.basename(file));
} else if (command === 'stats') {
console.log(`${store.notes.length} notes, ${stats.countWords(store.notes)} words`);
} else if (command === 'clear') {
rmSync('notes.json', { force: true });
console.log('Deleted notes.json');
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Node.js 기초의 모든 레슨
직접 연습해 보세요: Express 플레이그라운드