我无法检查是否已设置对象值。
我有:
regObj = {};
function setvalue() {
regObj.name = 'Bob';
}
function lateron() {
if (!regObj.name) { // only do this if regObj.name has not been set already
// perform some stuff
}
}
运行lateron
函数时,我收到错误"无法找到变量regObj"。
检查是否存在不会引发错误的正确方法是什么?
答案 0 :(得分:0)
试试这段代码
function lateron() {
//check regObj is defined or not and if defined then checked name is defined or not and if defined then checked its empty or not
if (typeof(regObj)!="undefined" && typeof(regObj.name )!="undefined" && regObj.name.trim()!="") {
// perform some stuff
}
}
感谢
答案 1 :(得分:-2)
尝试使用Object.hasOwnProperty()
函数来识别,
function lateron() {
if (!regObj.hasOwnProperty("name")) {
// perform some stuff
}
}