[从.txt文件加载列表时,数组出现indexOf问题

问题描述 投票:0回答:1

我正在开发一个相当简单的Web应用程序,该应用程序可以接受数字或单词形式的用户输入。这背后的基本前提是,如果我以单词开头和/或单词的索引号开头,则需要在数组中查找单词。我创建了一个可以同时实现这两个功能的函数。唯一要注意的是,如果我没有手动输入let generic_list = ["Item1", "Item2", "Item3"];之类的列表,则尝试从文本文件加载索引时找不到索引。

我用于加载文本文件的代码是:

$.get("list.txt", function(data) {
    let list_loaded = data.split("\n");
})

这是我用来手动创建列表的索引的代码。

let item_index = list_loaded.indexOf(item_index_im_searching_for);

当我手动创建列表时,返回值将是正确的索引号。如果文本文件加载列表,则该值将返回-1 undefined。我已经阅读了一些文章,但是我不确定自己缺少什么。希望你们中的一些JavaScript兽医可以引导我朝正确的方向发展。

此外,在控制台中进行测试时,两个列表看起来完全相同。

javascript jquery arrays
1个回答
0
投票

检查JSFiddle以获取与javascript indexOf方法有关的详细信息:https://jsfiddle.net/ecx8Lhtj/

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
var htmlText = "<p>Finding position of the first occurrence for word welcome from string is at "+ n +"</p>";

str = str.split(" ");
htmlText += "<p>Array Elements="+ str +"</p>";
htmlText += "<p>Also check CONSOLE for seeing array elements.</p>";
console.log(str);
n = str.indexOf("welcome");
htmlText += "<p>a. Finding position of the first occurrence for word welcome from array elements is at "+ n +"</p>";

n = str.indexOf("world");
htmlText += '<p>b. Finding position of the first occurrence for word welcome from array elements is at "world" '+ n +'</p>';

n = str.indexOf("world,");
htmlText += '<p>b. Finding position of the first occurrence for word welcome from array elements is at "world," '+ n +'</p>';

document.getElementById("displayText").innerHTML = htmlText;
<p>JavaScript String indexOf() Method, reference URL: https://www.w3schools.com/jsref/jsref_indexof.asp</p>
<p><h3>Definition and Usage</h3></p>
<p>The indexOf() method returns the position of the first occurrence of a specified value in a string.</p>
<p>This method returns -1 if the value to search for never occurs.</p>
<p><b>Note</b>: The indexOf() method is case sensitive.</p>
<p>Whenever indexOf used with array elements, it will try to find searching text as a complete text against each element from an array. If such match found then only it will return an index otherwise it will return -1.</p>
<p>Please see below examples:</p>
<p id="displayText"></p>

[每当我们对数组使用javascript indexOf方法时,它都会尝试查找与数组的每个元素完全匹配的搜索字符串。并且,如果找到完全匹配,则仅返回正确的索引值,否则返回-1。

© www.soinside.com 2019 - 2024. All rights reserved.