// The global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
// Change code below this line
function add (bookName, test) {
console.log('t', bookName)
let newB = bookName;
newB.push(test)
return newB;
// Change code above this line
}
// Change code below this line
function remove (bookName) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
bookName.splice(book_index, 1);
return bookName;
// Change 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(newBookList, newerBookList, newestBookList)
console.log(bookList);t [ "The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae" ] t [ "The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"
为什么会有两个字符串:“时间简史”和“简史”
时间的历史“它是在保存它的价值并再次使用它吗?它将如何
还记得在上一次函数调用中有一个简短的历史记录吗?
第三个全局变量中的函数调用是add(bookList,'A Brief
时间的历史‘)那么到底发生了什么?
如果你不明白我在说什么,基本上,我在试着修复
add()函数,它正在工作,但它运行了两次,因为它被分配给
两个变量,问题是在newestBookList中,add()
函数添加了字符串,但它将字符串添加到我创建的数组中
在add()函数中。
发布于 2021-06-08 02:26:45
按照您在let newB = bookName;行中命名变量的方式,这行代码并没有做您认为它正在做的事情。它并不是在创建bookName的新实例,它只是将在bookName参数上传递的现有数组引用赋给newB,该参数为bookList。
由于您继续传入bookList,并且没有使用[...bookName]或bookName.slice()之类的东西获得新的数组引用,因此它在每次后续调用时都会继续使用相同的数组。因此,它将继续将值推送到同一数组中。这就是为什么你会得到你正在得到的输出。
如何每次都返回一个新的数组引用的一个示例如下:
function add (bookName, test) {
console.log('t', bookName)
let newB = bookName.slice(); // generates a new array with the same elements
newB.push(test)
return newB;
}发布于 2021-06-08 02:49:24
问题是,当您在add函数中重新分配数组时,您只是传递了数组引用。这会导致原始数组
如果您打算使用bookList作为初始状态,并使用add和remove来更改和返回新状态。我在您的代码中看到的另一个问题是,在您的remove上,您还需要使用splice函数更改原始数组。如果您打算遵循此方法,我建议您进行以下更改,以确保您不会覆盖原始状态。
// The global variable
const initialBookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
function add(prev, bookName) {
return [...prev, bookName];
}
function remove(prev, bookName) {
const idx = prev.indexOf(bookName);
if (idx === -1) return [...prev];
return [
...prev.slice(0, idx),
...prev.slice(idx + 1, prev.length),
];
}
const bookList1 = add(initialBookList, 'A Brief History of Time');
const bookList2 = remove(initialBookList, 'On The Electrodynamics of Moving Bodies');
var bookList3 = remove(add(initialBookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log({
initialBookList,
bookList1,
bookList2,
bookList3,
})
https://stackoverflow.com/questions/67876828
复制相似问题