数组越界:与未定义的比较或长度检查? [英] Array Out of Bounds: Comparison with undefined, or length check?

查看:26
本文介绍了数组越界:与未定义的比较或长度检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个常见的 javascript 习惯用法:

this seems to be a common javascript idiom:

function foo (array, index) {
    if (typeof array[index] == 'undefined')
        alert ('out of bounds baby');
}

与更普遍(在其他语言中)和概念上更简单的相反:

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?

提示这个问题的代码示例可以在这里看到.在这种情况下,当在函数内部使用 'argument' 变量时,假设它将是一个连续数组不是很明智吗?

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.

可以为元素分配值 undefined.在这里使用它作为哨兵只是愚蠢.(可能存在其他有效且可能重叠的检查未定义的原因,但不是越界检查"——当给定 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆