[英]JavaScript beginner, if a variable does not match to do something
Basically what I'm trying to do is write a greasemonkey script so that if a link on a page is not a link I have on an ignore list to just open the link, if it is on the list then reload the page after 5 seconds here is what I tried so far 基本上,我要写的是编写润滑脂猴子脚本,这样,如果页面上的链接不是链接,我就可以在忽略列表中直接打开该链接,如果该链接在列表中,则在5秒钟后重新加载页面这是我到目前为止尝试过的
var url1 = $("span.capsulelink a:eq(0) ").attr("href");
var ignoreList = ["example1.com","example2.com"]
if (url1 !== ignoreList) {
window.open(url1);
} else {
setTimeout(function() {
location.reload();
},5000);
}
I know it's the ( url1 !== ignoreList
) part I am having trouble with, I just can not seem to find the right expression for that. 我知道这是我遇到麻烦的( url1 !== ignoreList
)部分,我似乎无法找到正确的表达方式。 Like I do not know how to say if url1
is not on the ignoreList
{do something}. 就像我不知道怎么说url1
是否不在ignoreList
。
ignoreList.indexOf(url1) !== -1
This is another way of saying "is url
contained in the ignoreList
array?" 这是另一种说法:“ url
包含在ignoreList
数组中?”
This is because the indexOf()
method of Array
returns the index of the element you're looking for, or -1
if the element doesn't exist. 这是因为Array
的indexOf()
方法返回要查找的元素的索引,如果该元素不存在,则返回-1
。
To negate this, which is what you want to do, you write: 要取消此操作(您要执行的操作),请输入:
ignoreList.indexOf(url1) === -1
(ie is url1
not in ignoreList
?) (即url1
不在 ignoreList
?)
This is a good question, because the answer really isn't intuitive. 这是一个很好的问题,因为答案确实不是直观的。
When you're starting to learn javascript
, some of the syntax patterns begin to look familiar. 当您开始学习javascript
,某些语法模式开始变得熟悉。
But the javascript equivalent of PHP's 但是,JavaScript相当于PHP的
if (!in_array([ARRAY]));
simply isn't obvious at all - this is one syntax you just need to know. 根本不是很明显-这是您只需要知道的一种语法。
Here is the javascript
you're looking for: 这是您要查找的javascript
:
if (ignoreList.indexOf(url1) !== -1) {
[RELOAD PAGE CODE HERE]
}
else {
[OPEN THE LINK CODE HERE]
}
Here's why it works: 这是它起作用的原因:
ignoreList.indexOf([VALUE])
looks through the ignoreList
array and searches through the array's items. ignoreList.indexOf([VALUE])
遍历ignoreList
数组并搜索该数组的项。
If one of those items is [VALUE]
, it returns the index of that item. 如果这些项目之一是 [VALUE]
,则返回该项目的索引。
Importantly, if none of the items are [VALUE]
it returns -1
. 重要的是,如果没有一个项目是[VALUE]
返回-1
。
So, in order to establish that at least one of the items is [VALUE]
, you have to verify that the returned index definitely isn't -1
. 因此,为了确定至少一项 是 [VALUE]
,您必须验证返回的索引肯定不是 -1
。
Consequently the condition you need to check for is: 因此,您需要检查的条件是:
if (ignoreList.indexOf(url1) !== -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.