js 对null取属性,返回null,如何实现?

let a = {a:'1'};
a.c   ====>  正常,为underfind

let b = null
b.s    =====> 会报错 Cannot read property 's' of null

如何实现 console.log(b.s) ====> 结果依然为 null

有一个model,用户输入查询条件,我不知道model是不是空的,所以代码里会写 model.id,这时model查不到,会报错。。。。。 if(model){ model.id } 我觉这种写法不优雅

阅读 2.1k
评论
    9 个回答
    • 12

    The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.