我在通过freeCodeCamp beta时遇到了一个奇怪的问题。
"目的"这不是修改原始数组并使用函数编程技术来修改数组。
但是我一直抱怨"阵列"参数是删除函数不是有效函数:
// 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 (bookListTemp, bookName) {
let newBookArr = bookListTemp;
return newBookArr.push(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 (bookList,bookName) {
let newArr = bookList.slice();
if (newArr.indexOf(bookName) >= 0) {
return newArr.slice(0, 1, bookName);
// 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);
在remove函数中,我尝试了参数并执行array.slice()方法以及array.concat()方法。由于做let newArr = bookList
实际上没有使新数组正确吗?它只是创建一个引用原始数组的新副本吗?
我得到的确切错误是TypeError: bookList.slice is not a function
甚至更奇怪的是Array.isArray(bookList)
返回true
(function remove
。所以我不明白为什么它抱怨数组方法?
答案 0 :(得分:3)
您的问题是Array.push
返回方法所在对象的新长度属性 调用。
你应该返回数组
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
newBookArr.push(bookName);
// Add your code above this line
return newBookArr;
}
或强> 让我们试试Array.concat
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
return newBookArr.concat(bookName);
// Add your code above this line
}
答案 1 :(得分:0)
有两种方法可以复制数组而不更改它。您将无法在bookList上使用.slice()
方法,因为它是函数中的参数,因此不是数组。解决方法是var newBookArr = Array.prototype.slice.call(bookListTemp);
或[].slice.call(bookListTemp);
这使您可以在bookList作为参数时执行切片。我发现的另一种方法是-var newBookArr = [].concat(bookListTemp);
尝试var newBookArr = [].push(bookListTemp);
时,我们发现原始bookList被推送到新数组中。因此它是一个副本,但作为数组中的一个数组。 .concat()
方法将旧数组合并为新数组。