我在 Angular 8 项目中使用 ng-bootstrap 中的 typeahead 元素,https://ng-bootstrap.github.io/#/components/typeahead/examples 。我正在使用库示例中给出的函数,但如果我的输入之一为空,我会收到错误。
我的组件类中有一个变量,它是用函数构建的:
searchAutofill = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
map(term => term.length < 1 ? []
: this.option.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 15))
)
option是一个字符串数组,例如:
[
"tom",
"bob",
"foo",
"emma",
null,
"john",
"hello",
"example",
当函数达到 null 值时,它返回ERROR TypeError: "v is null"
。如何更改代码以接受/忽略空值?
最佳答案
是的,因为您尝试对“null”值执行 String 方法。
所以在这里v.toLowerCase()
你得到null.toLowerCase()
。
每当您访问对象的任何属性或方法时,您必须确保该对象是您期望的对象。否则设置一些规则来检查,
在您的情况下,您似乎想检查字符串 v
中是否有一个子字符串保存在 term
变量中。
所以我猜测如果 v
为 null
,您希望返回 false
:
filter(v => v && v.toLowerCase().indexOf(term.toLowerCase()) > -1)
附:请注意,这里我只是检查 v
是否不是一个虚假值。您可能需要添加额外的规则来检查它是否是字符串。例如:
typeof v === 'string'
关于javascript - 当输入为 null 时,ngbtypeahead 函数返回 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58804639/