如何在数组的索引处查找值?

时间:2018-07-22 01:26:29

标签: javascript arrays

我似乎找不到任何东西。我正在遍历一个数组,我想检查每个索引是否不等于字符串“ deleted”。这是我的无效代码:

for (var i = 0; i < sessions.length-1; i++) {
    if (sessions[i] !== "deleted") {
        options += '<option value=\"' + (i+1) + '\">Session ' + (i+1) + '</option>';
    }
}

编辑:我两次做错了答案却没有答案怎么办? :(

1 个答案:

答案 0 :(得分:1)

您可以只使用indexOf函数来检查数组中元素的索引。如果元素不在数组中,则indexOf将返回-1。请记住,数组的索引从0而不是1开始。

var sessions = ["something", "something else", "deleted", "null", "a string", "another part of this array"];
console.log("Index of the word 'deleted': " + sessions.indexOf("deleted"));

var options = document.getElementById('options');
var sessions = ["something", "something else", "deleted", "null", "a string", "another part of this array"];
var index;
if ((index = sessions.indexOf("deleted")) != -1) {
  options.innerHTML += '<option value=\"' + (index + 1) + '\">Session ' + (index + 1) + '</option>';
}
<select id="options"></select>