JavaScript 过滤器方法返回过滤数组和空数组

JavaScript filter method returning filtered array and empty array

本文关键字:数组 过滤 返回 过滤器 方法 JavaScript      更新时间:2023-09-26

我正在尝试记录当前的读取状态,但不是只获取日志,而是在调用 displayInformation() 时也得到一个空数组。如何在没有额外空数组的情况下获得我想要的结果?为什么它返回一个空数组?

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."
[]

如何在没有额外空数组的情况下获得我想要的结果?

你必须使用.forEach()或普通for loop来做你想做的事情。 .filter()用例与您的用例完全不同。

为什么它返回一个空数组?

由于 .filter() 方法将返回一个过滤后的数组,因此在您的情况下,它会返回一个空数组,因为您的 callBack 函数一直在返回undefined


你的代码应该是这样的,

function displayInformation(library) {
 library.forEach(function(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 + '.'); 
    }
 });
}
displayInformation(library);

纯 for 循环版本,

function displayInformation(library) {
  var i = 0, len = library.length, obj;
  for (; i < len; i++) {
    obj = library[i];
    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 + '.');
    }
  }
}
displayInformation(library);

那是因为您打印出statusFilter这是使用statusRead过滤的结果。由于statusRead从不返回true,结果将为空。filter的工作方式是它将从旧数组创建一个新数组,其中包含返回 true 的每个值。例如,下面介绍如何从数字列表中获取所有偶数。

var evens = numbers.filter(function(x) {
  return x % 2 === 0;
});

所以,再一次,由于你永远不会从你的filter谓词返回true,你会得到一个空列表,你继续console.log出来。

要仅遍历列表,您应该使用 for 循环:

for (var i = 0; i < library.length; i++) {
  var obj = library[i];
  ...
}

或者forEach方法:

library.forEach(function(obj) {
  ...
});