[英]how can i find the index of an item array, to find if an item is in an array using javascript
I'm new to scripting and I was writing a script to find if a value is in an array. 我是脚本新手,我正在编写脚本来查找值是否在数组中。
/ html / / html /
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>account # a</p>
</body>
</html>
/ javascript / / javascript /
var cid = document.getElementsByTagName("P")[0].childNodes[0].nodeValue;
var res = cid.split(" ");
var customerid=res[2];
var abs=['a','b','c'];
var para = document.createElement("P");
var node = document.createTextNode("'"+customerid+"'");
para.appendChild(node);
document.body.appendChild(para);
var c=document.getElementsByTagName("P")[1].childNodes[0].data;
window.alert(abs.indexOf(c));
the alert window is showing the index as -1. 警报窗口显示索引为-1。 my plan was to use the following function if i can get the above code to get the correct index. 我的计划是使用以下函数,如果我可以获得上面的代码以获取正确的索引。
function check(){
if (abs.indexOf(c)>=0){
window.alert("item is in array");
}
}
check();
.indexOf()
will return -1
when the item is NOT in the array. .indexOf()
将返回-1
。 This is because if the item is in the first index of the array, it's at index 0
since arrays are zero-based. 这是因为如果该项在数组的第一个索引中,则它在索引0
因为数组是从零开始的。
For your check function, as mentioned above, 0
means that the element was found in the array in the first position. 对于您的check函数,如上所述, 0
表示在数组的第一个位置找到了元素。 So you'll want to check if .indexOf()
doesn't return -1 instead of greater than 0: 因此,您需要检查.indexOf()
是否不返回-1而不是大于0:
function check() {
if (abs.indexOf(c) !== -1){
window.alert("item is in array");
}
}
You could also use the ~
shortcut: 您也可以使用~
快捷方式:
function check() {
if (~abs.indexOf(c)){
window.alert("item is in array");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.