无法读取空的 属性 'length',javascript。检查给定的字符串是否包含字母:p & t
Cannot read property 'length' of null, javascript. Check if given string contain letters: p & t
我正在尝试调试我的 JS 迷你项目。其中一些,显示:
Uncaught TypeError: Cannot read property 'length' of null
at task(xx)
那些小项目可行,但我想删除所有错误。
此任务是关于:检查给定字符串是否包含相等数量的 p 和 t。
我关注了错误消息,据我所知,如果变量的长度为 null 或 0,这意味着这是未定义的,无法验证。所以,不成功,我尝试使用这段代码:
if (p < 0 || t< 0)
or
if (task55word == null)
基本代码在这里:
task55 = () => {
const task55word = document.getElementById("task55").value;
const task55ans = document.getElementById("task55ans")
const wordP = task55word.toLowerCase().match(/p/g);
const wordT = task55word.toLowerCase().match(/t/g);
const p = wordP.length;
const t = wordT.length;
if (p == t) {
task55ans.textContent = 'equal';
} else {
task55ans.textContent = 'not equal';
}
};
我做错了什么?
试试这个代码。 match
returns null
如果没有匹配项。
task55 = () => {
const task55word = document.getElementById("task55").value;
const task55ans = document.getElementById("task55ans");
const wordP = task55word.toLowerCase().match(/p/g) || "";
const wordT = task55word.toLowerCase().match(/t/g) || "";
const p = wordP.length;
const t = wordT.length;
if (p == t) {
task55ans.textContent = 'equal';
} else {
task55ans.textContent = 'not equal';
}
};
我正在尝试调试我的 JS 迷你项目。其中一些,显示:
Uncaught TypeError: Cannot read property 'length' of null at task(xx)
那些小项目可行,但我想删除所有错误。
此任务是关于:检查给定字符串是否包含相等数量的 p 和 t。
我关注了错误消息,据我所知,如果变量的长度为 null 或 0,这意味着这是未定义的,无法验证。所以,不成功,我尝试使用这段代码:
if (p < 0 || t< 0)
or
if (task55word == null)
基本代码在这里:
task55 = () => {
const task55word = document.getElementById("task55").value;
const task55ans = document.getElementById("task55ans")
const wordP = task55word.toLowerCase().match(/p/g);
const wordT = task55word.toLowerCase().match(/t/g);
const p = wordP.length;
const t = wordT.length;
if (p == t) {
task55ans.textContent = 'equal';
} else {
task55ans.textContent = 'not equal';
}
};
我做错了什么?
试试这个代码。 match
returns null
如果没有匹配项。
task55 = () => {
const task55word = document.getElementById("task55").value;
const task55ans = document.getElementById("task55ans");
const wordP = task55word.toLowerCase().match(/p/g) || "";
const wordT = task55word.toLowerCase().match(/t/g) || "";
const p = wordP.length;
const t = wordT.length;
if (p == t) {
task55ans.textContent = 'equal';
} else {
task55ans.textContent = 'not equal';
}
};