假设我们有以下 .filter 函数:
search(searchQuery: string) {
let results = myArray.filter(item =>
item.title.toLowerCase().includes(searchQuery) ||
item.description.toLowerCase().includes(searchQuery)
);
return results;
}
对于这个例子,我们可以认为 item
并不总是有 description
属性,只是在某些时候。
在这种情况下,函数将失败并出现错误:
ERROR TypeError: Cannot read property 'toLowerCase' of undefined
我们如何才能仍然在数组中搜索并仅在搜索中包含 description
属性(如果它存在)?这在 .filter()
函数中是否可行?
最佳答案
您可以采用默认值。
要么直接
(item.description || '').toLowerCase().includes(searchQuery)
或者使用默认值进行解构。
results = myArray.filter(({ title = '', description = '' }) =>
title.toLowerCase().includes(searchQuery) ||
description.toLowerCase().includes(searchQuery)
);
关于javascript - 我们可以将 .filter() 函数与搜索属性的条件规则一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55003714/