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

时间:2016-07-01 01:01:44

标签: javascript object ecmascript-6

我的代码如下:

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

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

1 个答案:

答案 0 :(得分:1)

未定义描述的值,您应首先检查:

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