JavaScript 过滤器方法返回过滤数组和空数组
JavaScript filter method returning filtered array and empty array
我正在尝试记录当前的读取状态,但不是只获取日志,而是在调用 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) {
...
});
相关文章:
- 使用一个键的值数组过滤多个javascript对象
- 根据另一个包含角度 js 中对象的数组过滤包含对象的数组
- Javascript:按字符串数组过滤对象数组
- 在 javascript 中使用数组过滤 for AngularJS
- 挖空和选择器的数组过滤问题
- Lodash 按数组的属性数组过滤
- 如何用另一个字符串数组过滤ng重复中的字符串数组
- 如何根据javascript数组过滤rss数据
- 基于NodeJS中的其他数组过滤/搜索对象的JavaScript数组
- 使用不带嵌套循环的数组过滤对象数组js
- 使用数组过滤数组Javascript
- 用一维数组过滤多维数组
- AngularJS:如何给值数组过滤
- Angularjs,逐个数组过滤
- 用另一个对象数组过滤Javascript对象数组
- 创建搜索栏以将数组过滤到表中
- 通过id数组过滤角度数据
- coffeescript -数组过滤不工作
- Backbone.js:如何通过模型ID数组过滤对象集合
- 使用基于嵌套值的数组过滤对象数组