问题描述
在调用函数的时候,有时候可能会忘了传入参数,这样会报错:
1
| TypeError: text is undefined
|
解决方案
使用参数的时候先判断参数是否存在,如果参数存在,再使用参数。
使用typeof运算符进行判断
1 2 3 4 5 6 7 8 9
| function mdCodeInLines(text) { if (typeof (text) == "undefined") { console.log("text=" + text) var text = input.value; } text = text.replace(/`?((?:-(?! ))?[a-zA-Z<][a-zA-Z0-9 ():\_.\/\[\]<>,+="]*[a-zA-Z0-9)>/.\*])`?/mg, "`$1`"); result(text) }
|
和null比较
1 2 3 4 5 6 7 8 9
| function mdCodeInLines(text) { if (text == null) { console.log("text=" + text) var text = input.value; } text = text.replace(/`?((?:-(?! ))?[a-zA-Z<][a-zA-Z0-9 ():\_.\/\[\]<>,+="]*[a-zA-Z0-9)>/.\*])`?/mg, "`$1`"); result(text) }
|
经过我的测试,这两种方式都可以,具体的区别我还没比较.