润滑猴测试数组元素是否存在

Greasemonkey testing if array element exists

本文关键字:是否 存在 数组元素 测试      更新时间:2023-09-26

我正在编写一个脚本,该脚本使用基于链接部分的数组中的元素为页面上的内容添加标签...所以我的数组看起来像这样:

var componentList[9] = "Sunnyseed"
var componentList[10] = "Echoberry"
var componentList[11] = "Riverstone"
var componentList[13] = "Auraglass"
var componentList[14] = "Skypollen"

您会注意到没有"12"... 我希望当数组项不存在时标签为"未知"。 现在,我无法完全测试我的解决方案,因为我无法导致目标页面向我抛出 12...所以我希望有人能告诉我这是否会做我想做的事......

 var component = ""
 if(typeof componentList[critterIDval] == 'undefined'){
 component="Unknown"
 }
else{
 component=componentList[critterIDval]
}

这显然不是完整的剧本,但它应该是重要的东西...... 我只想知道当小动物 IDval 为 12 岁时,这是否会让它说"未知" - 因为可能需要数年时间才能遇到这种情况进行测试。

你差不多就在那里。您在比较中使用了单等号,所以这会搞砸它,我不确定您是否可以创建这样的 JS 数组,但除此之外,您很好。

这是我为它运行的测试:

var componentList = [];
componentList[9] = "Sunnyseed";
componentList[10] = "Echoberry";
componentList[11] = "Riverstone";
componentList[13] = "Auraglass";
componentList[14] = "Skypollen";
for (var critterIDval = 9; critterIDval < 15; critterIDval++) {
    if (typeof componentList[critterIDval] == 'undefined') { // double equals here
        component = "Unknown";
    } else {
        component = componentList[critterIDval];
    }
    console.log(component);
}

看起来不错。

虽然如果你确定该值永远不会是一个空字符串(如componentList[14] = '';),那么你可以尝试

var component = componentList[critterIDval] || 'Unknown'

我希望当数组项不存在时标签为"未知"。

typeof 运算符不会告诉您属性是否存在,因为它会在属性不存在时返回 undefined,但当它确实存在并已分配值undefined或只是创建但尚未分配值时,也会返回 undefined

有两种

主要方法可以测试属性是否存在:in运算符(也查找[[Prototype]]链)和所有对象的hasOwnProperty方法。所以

if (componentList.hasOwnProperty(critterIDval)) {
  component = "Unknown"
} else {
  component = componentList[critterIDval]
}

你也可以写成:

component = componentList.hasOwnProperty(critterIDval)? componentList[critterIDval] : 'unknown';

还有其他方法,例如查看Object.keys(componentList)componentList.propertyIsEnumerable(critterIDval),但以上是最常见的。

编辑

如果你的要求不仅仅是测试属性是否存在,还要测试"真实"值,那么:

if (componentList[critterIDval])

可能就足够了,并且当值为 ''(空字符串)、0falseNaNundefinednull 时返回 false。

也许只测试一个非空字符串或数字就可以了:

if (/.+/.test(componentList[critterIDval]))

但这返回true NaNnull等。因此,您需要指定实际测试的内容,否则可能会得到某些值的意外结果。