我希望将用户在输入中输入的单词与我试图访问的API中的数组中的单词列表进行比较。例如,如果用户输入" Sun ",我想发出类似于“嘿,您得到了,Sun出现在7中”之类的警告,其中7将是包含包含单词"Sun“的字符串的数组位置。
代码正在查找的数组是movie.title
,它实际上是包含每个电影标题的电影列表。
问题是,我在这里发布的代码只处理if (movie.title.includes("Pom"))
中存在的includes()
中的硬编码字符串。我需要它来接受变量userWord
,但是当我使用该变量时,什么也不会发生。
此外,我如何能够指出包含匹配的数组位置?我不知道我是否足够清楚,我通常只是通读Stackoverflow。
我在这里发布的代码基本上是从一个在线教程中获得的。我试着在Vue中实现这一点(这就是我想做应用程序的地方),但是做不到,所以我使用了这段代码。我不知道这是不是在性能或写作方面最好的方式。
谢谢。
requestAndcheckIf: function () {
const request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function () {
// Begin accessing JSON data here
const data = JSON.parse(this.response);
data.forEach(movie => {
// Log each movie's title
console.log(movie.title);
if (movie.title.includes("Pom")) {
alert("Gotcha! It is present in the " + )
} else {
}
});
}
request.send();
发布于 2018-09-06 02:40:45
至于查找索引:
Array#forEach()
的语法如下:
arr.forEach(function callback(currentValue[, index[, array]]) {
//your iterator
}[, thisArg]);
这意味着,传递给回调函数的第二个参数是当前索引,您可以在这里使用它:
requestAndcheckIf: function() {
const request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function() {
// Begin accessing JSON data here
const data = JSON.parse(this.response);
data.forEach((movie, index) => {
// Log each movie's title
console.log(movie.title);
if (movie.title.includes("Pom")) {
alert("Gotcha! It is present in the " + index)
} else {
}
});
}
request.send();
}
但是,如果您只想查找某项内容的索引,则可以使用Array#findIndex()
requestAndcheckIf: function() {
const request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function() {
// Begin accessing JSON data here
const data = JSON.parse(this.response);
let index = data.findIndex(movie => movie.title.includes("Pom"));
alert("Gotcha! It is present in the " + index)
}
request.send();
}
发布于 2018-09-06 02:54:04
您还可以查看数组中可用的findIndex方法。
var index = data.findIndex(function findFirstLargeNumber(movie) {
return movie.title.includes("Pom") ;
})
在这里,索引应该给出您正在查找的索引
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
https://stackoverflow.com/questions/52191442
复制相似问题