通过新的FCC材料进行工作。肯定在零件方面有麻烦。我已经接近了这个,但是仍然不对,因为它没有通过最终测试:
“ newsBookList应该等于[“ Baskervilles的猎犬”,“PhilosophiæNaturalis Principia Mathematica”,“ Disquisitiones Arithmeticae”,“时间简史”]
当我console.log(newestBookList)时,我看到它正在删除正确的条目,但未添加“简要历史记录”。有什么建议么?我不清楚为什么这两种方法可以单独工作,但在这里不能一起工作,也不清楚如何使用BDD进行测试...
// the global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function add(arr, bookName) {
return arr.concat([bookName]);
}
// Add your code above this line
/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function remove(arr, bookName) {
if (bookList.indexOf(bookName) >= 0) {
var index = bookList.indexOf(bookName);
return bookList.slice(0, index).concat(bookList.slice(index + 1));
// Add your code above this line
}
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
//console.log(bookList);
//console.log(newBookList);
//console.log(newerBookList);
console.log(newestBookList);
最佳答案
您的remove
函数引用的是原始bookList
,而不是传递的数组。将所有bookList
引用更改为arr
引用(传递给remove
函数的参数):
// the global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function add(arr, bookName) {
return arr.concat([bookName]);
}
// Add your code above this line
/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function remove(arr, bookName) {
if (arr.indexOf(bookName) >= 0) {
var index = arr.indexOf(bookName);
return arr.slice(0, index).concat(arr.slice(index + 1));
// Add your code above this line
} else console.log('n');
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
const added = add(bookList, 'A Brief History of Time');
var newestBookList = remove(added, 'On The Electrodynamics of Moving Bodies');
//console.log(bookList);
// console.log(newBookList);
//console.log(newerBookList);
console.log(newestBookList);
不过,您可以考虑只检查一次
indexOf
:function remove(arr, bookName) {
var index = arr.indexOf(bookName);
if (index === -1) return;
return [...arr.slice(0, index), ...arr.slice(index + 1)];
}