小黑小波比.判断字段是否存在和字段值是否为空问题

1.判断字段是否存在。如果字段存在。才可以赋值,否则报错字段未定义

var a =1;

输入:a||2

返回 1

当输入:b||2

返回:1

报错信息:b未定义。所以要判断b定义了。先if(b) 如果定义了返回true 否则false 

ReferenceError: b is not defined
    at repl:1:2
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

2.当字段是一个数组,如果字段存在,子数组也存在。才可以给字数组中的字段赋值


var a ={"a1":1}

当输入:a.a1||3

返回:1

当输入a.a2||3

返回:3

当输入a.a2.b1||3

返回: b1未定义,所以要判断a2是否存在

报错信息:

TypeError: Cannot read property 'b1' of undefined
    at repl:1:6
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

你可能感兴趣的:(js,nodejs,小黑小波比)