如何读取对象中值的长度?

How do I read the length of a value within an object?

本文关键字:何读 取对象      更新时间:2023-09-26

我有下面的代码:

const minLocationLength = 1;
        if (location.description.length < minLocationLength) {
          reject(`Location must be at least ${minLocationLength} characters.`);
        }

我得到错误Cannot read property 'length' of undefined。我做得对吗?

description的值没有定义,您应该先这样检查:

 if (location.description && location.description.length < minLocationLength) {
          reject(`Location must be at least ${minLocationLength} characters.`);
        }