我在使用我的一个函数时遇到了问题。在哪一行有错误:Uncaught TypeError: Cannot convert undefined or null to object
。
我的功能是:
function hexConvert(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]); //The error is in this line
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
当我使用错误时的代码是安慰:-
var btn = $(".btn-3d");
btn.each(function(index, elem) {
var bgColor = $(this).css('backgroundColor');
hexConvert(bgColor);
$(this).css({
'box-shadow': '0px 4px 0px 0px' + ColorLuminocity(color, -0.1)
});
});
任何人都可以帮助我理解它吗?并得到解决
最佳答案
match
可以返回 null
(如果没有匹配),但是在调用 delete(parts[0] );
我不清楚您为什么想要从返回的数组中删除该条目(我可能会使用 shift
),但是如果您这样做(或者如果您使用shift
),你需要一个 null
守卫:
function hexConvert(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (!parts) { // <====
color = null; // <====
return; // <====
} // <====
delete parts[0]; // <==== `delete` isn't a function, no need for parens
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
然后当你使用它时:
hexConvert(bgColor);
if (color) {
$(this).css({
'box-shadow': '0px 4px 0px 0px' + ColorLuminocity(color, -0.1)
});
}
旁注:让 hexConvert
使用全局变量是一个非常糟糕的主意。相反,让它返回结果:
function hexConvert(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (!parts) { // <====
return null; // <====
} // <====
delete parts[0]; // <==== `delete` isn't a function, no need for parens
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
return '#' + parts.join('');
}
然后当你使用它时:
var color = hexConvert(bgColor);
if (color) {
$(this).css({
'box-shadow': '0px 4px 0px 0px' + ColorLuminocity(color, -0.1)
});
}
关于javascript - 未捕获的类型错误 : Cannot convert undefined or null to object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763067/