2015-12-21 59 views
0

的“取代”我想所有的数组元素转换为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。我应该如何改变我的代码来实现这一目标?

+0

尝试设置'undefined'到报价=>''undefined'' – messerbill

回答

4

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; 
    } 
} 
2

typeof MyThing[i] === undefinedMyThing[i] === undefinedtypeof 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; 
} 

但同样要注意的事情有关""

+0

@TJ,'如果(MyThing [I] )''也会对'undefined''返回true。 – Rajesh

+0

@Rajesh:当然它会的,'替换'会对此起作用,因为它是一个字符串。但我不认为OP在数组中有'undefined',只是'undefined'和'null'。 –

0

我想这是一个错字错误,请尝试报价内的推杆未定义:

if (typeof MyThing[i] === 'undefined') {