我想記錄當前的閱讀狀態,而不是隻得到日誌我調用displayInformation()時也得到一個空數組。如何獲得我想要的結果而不需要額外的空數組?爲什麼它返回一個空數組?JavaScript過濾器方法返回過濾陣列和空數組
function displayInformation() {
function statusRead(obj){
if (obj.readingStatus === false) {
console.log('You still need to read ' + obj.title + ' by ' + obj.author + '.');
} else {
console.log('Already read ' + obj.title + ' by' + obj.author + '.');
}
}
var statusFilter = library.filter(statusRead);
console.log(statusFilter);
}
var library = [
{
title: 'Bill Gates',
author: 'The Road Ahead',
readingStatus: true
},
{
title: 'Steve Jobs',
author: 'Walter Isaacson',
readingStatus: true
},
{
title: 'Mockingjay: The Final Book of The Hunger Games',
author: 'Suzanne Collins',
readingStatus: false
}
];
displayInformation();
當你調用displayInformation()這是什麼登錄到控制檯
"Already read Bill Gates byThe Road Ahead."
"Already read Steve Jobs byWalter Isaacson."
"You still need to read Mockingjay: The Final Book of The Hunger Games by Suzanne Collins."
[]
你'statusRead()'是'返回undefined',這是爲什麼'Array.filter()'正在刪除這些元素。相反,你應該使用'library.forEach(statusRead)' – Nayuki
在你使用一個不熟悉的方法之前,[閱讀它的文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/陣列/過濾器)。然後你會知道它是如何工作的,以及是否正確的方法來解決你的問題。 –