外出数组prevent的javascript [英] Prevent javascript from going out of an array
问题描述
有什么办法我可以,如果我尝试进入一个不存在的数组索引下探错误prevent的JavaScript?
Is there any way I can prevent javascript from dropping an error if I try to go into a non existing array index?
例如:数组[-1]
将返回错误,并最终打破了所有我的code。我怎样才能让它只返回未定义,让我的剧本去?我可以检查阵列(这样,如果指数大于零或大或小比数组大小它将跳过)之前实现一个if语句,但这将是非常乏味!
Example: array[-1]
would return error and eventually break all my code. How can I let it just return 'undefined' and let my script go on? I can implement an if statement before checking the array (so that if the index is minor than zero or major than the array size it would skip it) but this would be very tedious!
这是我的code:
if (grid[j-1][i])
n++;
if (grid[j+1][i])
n++;
if (grid[j][i+1])
n++;
if (grid[j][i-1])
n++;
if (grid[j-1][i-1])
n++;
if (grid[j+1][i+1])
n++;
if (grid[j-1][i+1])
n++;
if (grid[j+1][i-1])
n++;
有两个回路其中两个看到J和我从零开始内。我不想改变他们既不写另一个if语句(你可以看到,已经有太多的人!)。有没有什么解决办法吗?
It is inside of two loops which both sees J and I starting from zero. I don't want to change them and neither writing another if statement (as you can see, there are already too much of them!). Is there any solution?
谢谢!
推荐答案
如果你知道你的网格的措施,你可以把前哨细胞的周围。
If you know the measures of your grid, you can put "sentinel cells" around it.
如果您添加第-1索引到一个数组 X
,它并没有算到 x.length
。把一个额外的最后一个元素到列表中会增加 x.length
。
If you add a -1st index to an array x
, it does not count to x.length
. Putting an additional last element into the list would increment x.length
.
我敢说使用定点细胞的算术计算由d_inevitable提到的将是最快的解决方案相结合的算法,因为它不涉及分支机构。你甚至可以省略 !!
,因为真正
将评估为1,假
0的均衡。
I daresay using sentinel cells combined with the arithmetic counting algorithms mentioned by d_inevitable would be the fastest solution, since it would not involve branches. You even can omit the !!
because true
will evaluate to 1 and false
to 0 in an equalization.
不要使用指数-1。它较慢的非常多,正常的数组索引。请参见 http://jsperf.com/index-1 。
Do not use index -1. Its an awful lot slower that normal array indexes. See http://jsperf.com/index-1.
这篇关于外出数组prevent的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!