Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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 } 我觉这种写法不优雅


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

let b=null表示b是一个不存在的对象,不存在的对象哪来的属性?所以报错
let b= {};这样b是一个空对象,b.s取空对象中不存在的属性才会输出underfind的。

你的需求本身就是反javascript的。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...