[英]Array.slice() parameter is not a function
我在通過freeCodeCamp beta時遇到一個奇怪的問題。
這樣做的“目的”不是修改原始數組,而是使用功能編程技術來修改數組。
但是,我一直在抱怨“ array”參數是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 (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
。所以我不明白為什么它抱怨數組方法?
您的問題是Array.push
return調用該方法的對象的新length屬性。
您應該返回數組
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
}
有兩種方法可以復制數組而不更改它。 您將無法在.slice()
上使用.slice()
方法,因為它是函數中的參數,因此不是數組。 解決方法是var newBookArr = Array.prototype.slice.call(bookListTemp);
或[].slice.call(bookListTemp);
這使您可以在bookList作為參數時對它進行切片。 我發現的另一種方法是: var newBookArr = [].concat(bookListTemp);
當嘗試var newBookArr = [].push(bookListTemp);
我們發現將原始bookList推送到新數組中。 因此它是一個副本,但作為數組中的一個數組。 .concat()
方法將舊數組合並為新數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.