测试关联数组中是否存在密钥 [英] Testing Whether A Key Exists In An Associative Array

查看:56
本文介绍了测试关联数组中是否存在密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个javascript新手,在一个脚本上工作,检查是否有一个

" path"从一个阵列中的一个元素到另一个元素被阻止。目前,

脚本将已处理的单元格索引(因此为整数)

压入数组。为了防止重新检查已处理的单元格,

脚本遍历(sorted)数组以查看该整数是否为
是数组的元素。


在阅读了javascript数组之后,我想或许它会更好地尝试一个类似perl的解决方案,使用associative
$ b $ b阵列因为我会在perl中使用哈希。在perl中,我会通过

来执行此操作,只需检查是否为特定键定义了哈希元素。

这样可以避免检查数组中的每个值。


我的%chked_cells;

我的$ this_cell;


if(!defined $ chked_cells {$ this_cell}){

$ chked_cells {$ this_cell} = 1;

}


在javascript中,据我所知,相应的代码会看看

这样的事情:


var chked_cells = new Array;

var this_cell;


if(!chked_cells [this_cell]){

chked_cells [this_cell] = true;

}


但是,我认为这不起作用,因为没有javascript等价的

到perl'''定义的'"函数(和javascript处理undefined

变量不同,我认为)。在javascript中,此代码段会返回一个

错误,说明chked_cells没有任何属性。我不能用b $ b来弄清楚如何以类似的方式进行测试,虽然我已经看过测试

a变量以查看它是否未定义,我还没能够make

在这里工作(因为数组是定义的?)。


有没有办法以这种方式使用关联数组?有没有更优惠的方式?


非常感谢。

解决方案

this_cell;


if(!defined


chked_cells {


this_cell}){

I am a javascript newbie working on a script that checks whether a
"path" from one element in an array to another is "blocked." Currently,
the script pushes an already processed cell index (hence an integer)
into an array. To prevent rechecking already processed cells, the
script iterates through the (sorted) array to see whether that integer
is an element of the array.

After reading about javascript arrays a bit more, I thought perhaps it
would be better to try a perl-like solution, using an "associative
array" as I would use a hash in perl. In perl, I would do this by
simply checking whether a hash element is defined for a particular key.
This avoids checking each value in the array.

my %chked_cells;
my $this_cell;

if (! defined $chked_cells{$this_cell}){
$chked_cells{$this_cell} = 1;
}

In javascript, as far as I can tell, the corresponding code would look
something like this:

var chked_cells = new Array;
var this_cell;

if (!chked_cells[this_cell]){
chked_cells[this_cell] = true;
}

But, I think this doesn''t work because there is no javascript equivalent
to the perl''s "defined" function (and javascript handles undefined
variables differently, I think). In javascript, this snippet returns an
error saying that chked_cells doesn''t have any properties. I cannot
figure out how to do the test in similar way, though I have seen testing
a variable to see whether it is undefined, I haven''t been able to make
that work here (because the array is defined?).

Is there a way to use an associative array in this way? Is there a
better way?

Thanks very much.

解决方案

this_cell;

if (! defined


chked_cells{


this_cell}){


这篇关于测试关联数组中是否存在密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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