【发布时间】:2015-06-22 14:13:54
【问题描述】:
我想要什么
我正在尝试使用 typeof 来检查数组元素是否存在。原因是为了防止Cannot read property '0' of null 错误。但是,只是尝试检查元素是否存在会导致错误。
我的尝试
if (typeof foo[0] !== 'undefined')
{
// I want to get here
}
和
if (typeof(foo[0]) !== 'undefined')
{
// I want to get here
}
这是循环的一部分,前四次迭代有效,第五次假定无效,第六次假定有效。但是,它在第五个循环中失败了。我不能写异常,因为输入可以改变循环的哪些迭代应该工作,哪些不应该工作。
我相信这是正确的方法,我不应该根据这些 stackoverflow 答案收到这种行为。
Check if an array item is set in JS
Checking if a key exists in a JavaScript object?
How to check if a multidimensional array item is set in JS?
我认为关键在于 typeof 是您可以在尝试使用元素之前检查是否设置了元素并给自己抛出错误。其他用户似乎可以使用完成此操作。我猜我正在做一些不同的事情。如何检查是否设置了数组索引而不使脚本失败,因为我正在查看未设置的数组索引。
更多上下文中的代码
应该不是必需的,只是装箱。
for (templ_i=0; templ_i<number_of_fields; templ_i++)
{
// Font size
if (d['font_size_group'][templ_i]['font_size'])
{
size_re = new RegExp('"text_' + line + '" font-size="\\d+(\\.[0-9]+)?"', 'g');
current_line = svg_template.match(size_re);
size_re = new RegExp('[^_"]\\d+(\\.[0-9]+)?', 'g');
if (typeof current_line[0] !== 'undefined') { current_font_size = current_line[0].match(size_re); }
console.log(current_font_size);
}
}
【问题讨论】:
-
您了解短路语句的工作原理吗?你的 foo 是 undefined/null 所以它没有索引的孩子。你最好把 if 语句短路到
if (foo && foo[0])不需要“typeof” foo[0] 测试它是否为空/未定义,如果不是返回 true 如果它是 null 返回 false ...除非 foo [ 0] 是一个布尔值,那么是的,您可能需要特别检查它是否不等于 undefined/null
标签: javascript jquery arrays