无法读取 null 的属性 'includes'"

sof*_*tya 3 javascript vue.js vuejs2

我在 JavaScript 中使用 Vue.js。

我有一个被调用的对象数组,products每个对象都有被property调用的smallest_unit_barcode. 我只想过滤带有条形码的产品value,所以我做了这个功能:

if (value != '') {
    var results = this.products.filter(obj=>obj.smallest_unit_barcode.includes(value));
    var results = results.slice(Math.max(results.length - 20, 0))
    this.pos_quick_lunch = results;
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但如果obj.smallest_unit_barcode == null,我收到此错误:

Error in v-on handler: "TypeError: Cannot read property 'includes' of null"
Run Code Online (Sandbox Code Playgroud)

null过滤产品数组时如何忽略该值?

Fel*_*ing 8

null在尝试访问该属性之前进行比较:

obj => obj.smallest_unit_barcode !== null && obj.smallest_unit_barcode.includes(value)
Run Code Online (Sandbox Code Playgroud)

因为&&短路,所以如果左操作数的计算结果为假,则不会计算右操作数。