数组出界:与不确定,或长度检查比较? [英] Array Out of Bounds: Comparison with undefined, or length check?
问题描述
这似乎是一个常见的JavaScript成语:
this seems to be a common javascript idiom:
function foo (array, index) {
if (typeof array[index] == 'undefined')
alert ('out of bounds baby');
}
,而不是更prevalent(在其他语言)并且从概念上简单的:
as opposed to the more prevalent (in other languages) and conceptually simpler:
function foo (array, index) {
if (index >= array.length)
alert ('boo');
}
据我所知,第一种情况还将为这对他们有'空白'阵列工作,但是是一个共同的足够的情况下,以保证成语?
I understand that the first case will also work for arrays which have 'gaps' in them, but is that a common enough case to warrant the idiom?
这促使这个问题的code样品可以看出<一个href=\"http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436\">here.在这种情况下,使用函数内的'参数'变量的时候,是不是理智的假设,这将是一个连续的阵列?
The code sample that prompted this question can be seen here. In this case, when using the 'argument' variable inside a function, isn't it sane to assume that it will be a contiguous array?
推荐答案
唯一的正确的方法是检查该指数与长度。
The only correct way is to check the index vs. the length.
一个元素可以被分配值未定义
。它仅仅是傻的在这里使用它的定点。 (可能还有其他的,有效的和可能重叠,原因检查不确定的,而不是一个出界检查 - 在其他问题code将present可以说是错误的结果,当值给定的arg是的真正的未定义
)
An element may be assigned the value undefined
. It is just silly to use it for a sentinel here. (There may be other, valid and possibly overlapping, reasons for checking for undefined, but not "for an out of bound check" -- the code in the other question will present arguably wrong results when the value of the given arg is really undefined
.)
快乐编码。
这篇关于数组出界:与不确定,或长度检查比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!