如何删除此JavaScript空错误?
我使用以下命令根据斜杠后url的最后一个单词创建if语句:如何删除此JavaScript空错误?,javascript,Javascript,我使用以下命令根据斜杠后url的最后一个单词创建if语句: // Sticky var match = location.search.match(/(\w+)$/)[0]; if (match === 'complete') { $('p:has(audio)').addClass('sticky-child'); $('p:has(audio)').appendTo('.lesson_lang_switch'); } 问题是,首页的URL末尾没有任何单词
// Sticky
var match = location.search.match(/(\w+)$/)[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
问题是,首页的URL末尾没有任何单词(斜杠后):
www.example.com/
所以我得到了这个错误:
Uncaught TypeError: Cannot read property '0' of null
如何才能避免出现错误?您可以添加条件检查。i、 e
var match = (location.search.match(/(\w+)$/))
? location.search.match(/(\w+)$/)[0]
: "";
if (match === 'complete') { // match will be "" if the above is false
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
您可以检查是否发现类似以下内容:
var match = location.search.match(/(\w+)$/);
if(match != null){
match = match[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
}
var match = location.search ? location.search.match(/(\w+)$/)[0] : undefined;
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
您必须检查搜索是否确实存在。您可能希望执行以下操作:
var match = location.search.match(/(\w+)$/);
if(match != null){
match = match[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
}
var match = location.search ? location.search.match(/(\w+)$/)[0] : undefined;
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
location.search?
如果在location.search中有值,则返回true。如果返回,则正则表达式将完成。否则它将得到未定义的值
出现此错误的原因是location.search
没有任何值。正则表达式返回null
。由于您试图从null
读取[0]
,因此将出现此错误。您可以检查值是否为null
:
// Sticky
var loc = "www.example.com/";
var match = loc.match(/(\w+)$/) === null ? "" : loc.match(/(\w+)$/)[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
string.match返回包含匹配结果的数组,如果没有匹配项,则返回null。说到这里,我建议您在尝试应用location.search.match并对其编制索引之前,先检查location.search.match返回的内容
例如:
var matches = location.search.match(/(\w+)$/);
if(matches){
var match = matches[0];
if (match === 'complete') {
$('p:has(audio)').addClass('sticky-child');
$('p:has(audio)').appendTo('.lesson_lang_switch');
}
}
请查看您是否想进一步了解JavaScript的string.match方法。这不是最有效的方法。现在,您将执行两次正则表达式。好吧,你可以只做一次。没错,但是浏览器会缓存结果,所以这与做两个单独的正则表达式测试并不完全相同。我想在现实中,你需要知道结果失败的频率是否比它通过的频率更高。它是否缓存了它?你有证据吗?浏览器会在后台缓存集合。这是我不久前学习的东西。我会把它挖出来(即现代浏览器),所以我有点搞错了,缓存是浏览器选择器引擎,不一定是计算,但是似乎显示再次使用相同的正则表达式在第二轮时速度更快,所以可能正在使用类似的函数。