javascript - 在nodejs中检查null仅得到 "Cannot read property ' 1' of null"

标签 javascript node.js if-statement

我正在尝试测试字符串中 # 后面的空值。我尝试了各种方法,但在提交测试数据时总是出现 Cannot read property '1' of null 。我已经找出了我能想到的错误,但我似乎无法绕过这个错误。请记住,我是这方面的初学者,自从 cobol 时代以来我就没有编程过,我最后一次使用 javascript 是在 2000 年代初期。

//开始测试数据,可能通过的5个字符串

elt.message = '#1a' //goes through the script good
elt.message = '#12b' // goes through
elt.message = '#123c' //goes through
elt.message = '' //is ignored
elt.message = '# ' //crashes server

//测试数据结束

//First lets test to see if # is in the message. If true then we will parse it and add it to the database.
var str = elt.message;
var substr = '#';
var vtest = str.indexOf(substr) > -1;
if (vtest == 1){
var Vname = elt.author;
console.log('We tested for # and the value is true');

//extracts the number and the letter after the # from incoming chat messages
var test = elt.message; // replace with message text variable. 
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
if (pstr) {
var numbers = pstr[1];
var character = pstr[2];
var chupp = character.toUpperCase(); //Converts the lowercase to uppercase
}

//Tests to see if neither the question number or the possible answer is left out
//if (pstr[1] !== '' && pstr[2] !== ''){ //doesn't work =(
if (pstr[1] !== null && pstr[2] !== null){ //doesn't work either =(

console.log('we processed the numbers after the #sign and assigned the numbers and letter into variables.')
console.log('The question number is: ' + pstr[1]);
console.log('The letter processed is: ' + pstr[2]);

// Grabs the date and converts it into the YYYYMMDD string.
var dobj = new Date();
var dstr = dobj.toString();
var dsplit = dstr.split(' ');
let currentdate = `${dobj.getMonth() < '9' ? `0${dobj.getMonth() + 1}` :
  dobj.getMonth() + 1}`;
  currentdate = `${dsplit[3]}${currentdate}${dsplit[2]}`;
console.log(currentdate)//remove when done

//checks to see what the highest question number is in the database
var sel = con.query("SELECT * FROM questions WHERE ClassID = "+ currentdate + " ORDER BY QuesID DESC LIMIT 1", function (err, result){
    if (err) throw err;
    console.log('Total number of question records: '+result[0].QuesID);
    console.log('the script is querying with' + pstr[1]);
    console.log('the scripts answer letter is ' + pstr[2]);

    if (pstr[2] != '' && pstr[1] <= result[0].QuesID ){
        var query =  con.query("SELECT * FROM questions WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1], function (err, result) { // Selects the record based on the Date and the question number variables provided above
        if (err) throw err;
        console.log('it got past the test')

    if (result[0].AnsweredFirst === '' && result[0].AnswerLetter === chupp) { //Test to see if the AnsweredFirst is empty and that the Answer letter matchs with whats on file
    console.log('MATCH!');//remove when done

    var sql = "UPDATE questions SET AnsweredFirst = '"+ Vname + "' WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1]; //Updates the record with the first person who answered the question in the AnsweredFirst field
     con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(Vname + " answered question " + pstr[1] + " First!");
     });
    }
  });
 }
});
} else {
    console.log('Either the question number or the letter was left blank so we are skipping'); //the viewer did not put in a proper number and letter after the # sign
    }
} else {
    console.log('No signs of # so skipping queries') //if there is no # sign the message is not processed 
    };

我添加了脚本的其余部分以获得更好的想法。消息从聊天客户端传递到服务器。

我将尝试将代码块移动到第一个 if 语句中。我知道这很困惑,但说实话,我很惊讶我能走到这一步。

最佳答案

var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);

表示如果没有找到与您的正则表达式匹配的内容,则 pstrnull

在这种情况下,pstr 的任何索引(如 pstr[1]、pstr[2])都会抛出您所描述的错误:

Cannot read property 'n' of null

解决方案:

在使用索引之前,检查变量是否有值

if(pstr !== null) {
    // do something with pstr[1]
}

编辑:

nnnnnn正确地指出,您不能在字符串中显式存储空值。

关于javascript - 在nodejs中检查null仅得到 "Cannot read property ' 1' of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45428305/

相关文章:

javascript - 为什么 window.addEventListener ('scroll' , this.someScrollHandler, false) 在 IE 10 上不起作用?

javascript - 如何删除事件处理程序 document.onkeydown?

node.js - 将请求 header 添加到 Node 中的 Azure Application Insights 事件

node.js - Node Passport 错误 : Unknown authentication strategy "local-login"

java - "If"语句替代

Python 3.5 if 语句嵌套字典数据 : TypeError

javascript - 如何跟踪用户点击浏览器上的后退按钮

javascript - 如何从我的 Eclipse 项目中删除 javascript 验证?

node.js - Heroku 使用 React 和 Tailwind 构建失败

linux - 为什么在构建这个简单的 if else 语句时会出现错误 "Unary Operator Expected"?