无法读取属性未定义的错误
的“取代”我想所有的数组元素转换为null
如果有的undefined
:无法读取属性未定义的错误
console.log(MyThing[7]); //undefined.
for (var i = 0; i < 8; i++) {
if ($(".row.mine") != null) {
if (typeof MyThing[i] === undefined) {
MyThing[i] = null;
} else {
MyThing[i] = MyThing[i].replace(/Aa.*/, '').replace("-", "");
}
} else {
if (typeof MyThing[i] === undefined) {
MyThing[i] = null;
}
}
}
但是,这给了我一个错误Cannot read property 'replace' of undefined
。所以元素不会被转换,如果他们是undefined
。我应该如何改变我的代码来实现这一目标?
typeof MyThing[i] === undefined
总是为false,因为typeof运算符总是返回一个字符串。使用下列之一:
typeof MyThing[i] === 'undefined'
MyThing[i] === undefined
而且这并不检查值null
(为typeof null === 'object'
)。正如我所见,你可以有空值,所以你遇到的下一个错误可能是Cannot read property 'replace' of null
。
我建议你直接检查字符串类型:
if ($(".row.mine") != null) {
if (typeof MyThing[i] !== 'string') {
MyThing[i] = null;
} else {
MyThing[i] = MyThing[i].replace(/Aa.*/, '').replace("-", "");
}
} else {
if (typeof MyThing[i] !== 'string') {
MyThing[i] = null;
}
}
typeof MyThing[i] === undefined
应MyThing[i] === undefined
或typeof MyThing[i] === 'undefined'
,为typeof
总是给你一个串。
但在你的情况下,我只是用事实undefined
是falsey:
if (!MyThing[i]) {
MyThing[i] = null;
} else {
MyThing[i] = MyThing[i].replace(/Aa.*/, '').replace("-", "");
}
除非MyThing[i]
可能是""
,你不希望转换为null
。
还是在积极的进行表达:
if (MyThing[i]) {
MyThing[i] = MyThing[i].replace(/Aa.*/, '').replace("-", "");
} else {
MyThing[i] = null;
}
但同样要注意的事情有关""
。
@TJ,'如果(MyThing [I] )''也会对'undefined''返回true。 – Rajesh
@Rajesh:当然它会的,'替换'会对此起作用,因为它是一个字符串。但我不认为OP在数组中有'undefined',只是'undefined'和'null'。 –
我想这是一个错字错误,请尝试报价内的推杆未定义:
if (typeof MyThing[i] === 'undefined') {
尝试设置'undefined'到报价=>''undefined'' – messerbill