Javascript:循环使用TypeError属性未定义的对象 [英] Javascript: Looping an object with TypeError property undefined
问题描述
我有一个名为 xs
的对象数组,该对象存储名称
I have an array of object called xs
that store name
xs = [
{name: "Peter"},
{name: "Doe"},
{name: "Parker"},
{name: "John"}
];
并且我有一个setEmptyStr函数,如果未定义变量,该函数将返回空字符串
and i have a function setEmptyStr that return empty string if variable is undefined
function setEmptyStr(v) {
if(typeof v !== 'undefined'){
return v;
} else {
return '';
}
}
我尝试循环我的对象数组(长度比其自身数组长),我的数组长度为4,我尝试5,并且我不想使用array.length;
I try to looping my array of object (with more length than the array it self), my array length is 4, i try 5. and i dont wanna use array.length;
for (var i = 0; i < 5; i++) {
console.log(setEmptyStr(xs[i].name));
}
这四个名称返回成功,因为它不是未定义的.但是第五个就是返回
the 4 names are return successful because it is not undefined. But the 5th is return
TypeError属性名称"未定义.
TypeError property 'name' is undefined.
>>Peter
>>Doe
>>Parker
>>John
未捕获的TypeError:无法读取未定义的属性名称"
Uncaught TypeError: Cannot read property 'name' of undefined
我希望5号返回一个空字符串.我怎样才能做到这一点?我的代码有错误吗?
I want the 5th is return an empty string. How can i do this? Is there is an error in my code?
>>Peter
>>Doe
>>Parker
>>John
>>""
推荐答案
使用此:
xs = [
{name: "Peter"},
{name: "Doe"},
{name: "Parker"},
{name: "John"}
];
for (var i = 0; i < 5; i++) {
console.log(setEmptyStr(xs[i] && xs[i].name));
}
function setEmptyStr(v) {
if (typeof v !== 'undefined') {
return v;
} else {
return '';
}
}
首先测试 xs [i]
可以防止错误尝试访问 undefined
的属性.
Testing xs[i]
first prevents an error from trying to access a property of undefined
.
这篇关于Javascript:循环使用TypeError属性未定义的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!