gpt4 book ai didi

javascript - Array.slice() 参数不是函数

转载 作者:行者123 更新时间:2023-11-30 09:35:58 25 4
gpt4 key购买 nike

我在使用 freeCodeCamp beta 时遇到了一个奇怪的问题。

这样做的“目的”不是修改原始数组,而是使用函数式编程技术来修改数组。

但是,我不断收到关于“array”参数的提示,因为删除函数不是有效的函数:

//  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);

在删除函数中,我尝试获取参数并执行 array.slice() 方法以及 array.concat() 方法。因为执行 let newArr = bookList 实际上并没有使新数组正确吗?它只是创建了一个引用原始数组的新副本,正确吗?

我得到的确切错误是TypeError: bookList.slice is not a function

更奇怪的是Array.isArray(bookList)返回true(在函数remove中。所以我不明白为什么它是提示数组方法?

最佳答案

您的问题是Array.push

return The new length property of the object upon which the method was called.

你应该返回数组

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
}

关于javascript - Array.slice() 参数不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com