我在使用 freeCodeCamp beta 时遇到了一个奇怪的问题。
\n\n这样做的“目的”不是修改原始数组,而是使用函数式编程技术来修改数组。
\n\n然而,我不断收到关于“array”参数的抱怨,因为删除函数不是有效的函数:
\n\n// the global variable\nvar bookList = [\n "The Hound of the Baskervilles",\n "On The Electrodynamics of Moving Bodies",\n "Philosophi\xc3\xa6 Naturalis Principia Mathematica",\n "Disquisitiones Arithmeticae"];\n\n/* This function should add a book to the list and return the list */\n// New parameters should come before the bookName one\n\n// Add your code below this line\nfunction add (bookListTemp, bookName) {\n let newBookArr = bookListTemp;\n return newBookArr.push(bookName);\n // Add your code above this line\n}\n\n/* This function should remove a book from the list and return the list */\n// New parameters should come before the bookName one\n\n// Add your code below this line\nfunction remove (bookList,bookName) {\n let newArr = bookList.slice();\n if (newArr.indexOf(bookName) >= 0) {\n\n return newArr.slice(0, 1, bookName);\n\n // Add your code above this line\n }\n}\n\nvar newBookList = add(bookList, \'A Brief History of Time\');\nvar newerBookList = remove(bookList, \'On The Electrodynamics of Moving Bodies\');\nvar newestBookList = remove(add(bookList, \'A Brief History of Time\'),\n \'On The Electrodynamics of Moving Bodies\');\n\nconsole.log(bookList);\nRun Code Online (Sandbox Code Playgroud)\n\n在删除函数中,我尝试获取参数并执行 array.slice() 方法以及 array.concat() 方法。自从做了let newArr = bookList实际上并没有使新数组正确吗?它只是创建一个引用原始数组的新副本,正确吗?
我得到的确切错误是TypeError: bookList.slice is not a function
更奇怪的是Array.isArray(bookList)返回true(在function remove. 所以我不明白为什么它抱怨数组方法?
你的问题是Array.push
return 调用该方法的对象的新 length 属性。
你应该返回数组
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
newBookArr.push(bookName);
// Add your code above this line
return newBookArr;
}
Run Code Online (Sandbox Code Playgroud)
或者 让我们尝试Array.concat代替
function add (bookListTemp, bookName) {
let newBookArr = bookListTemp;
return newBookArr.concat(bookName);
// Add your code above this line
}
Run Code Online (Sandbox Code Playgroud)