[英]JavaScript, API, filtering array
I want to start function which create me table, iam using if
and indexOf
in .foreach, and i wish that shows me the table ony if the value of input will be exactly the same as a first item of array in tah case name:germany. 我想开始创建表的函数,我在.foreach中使用
if
和indexOf
,我希望如果输入的值与tah案例名称:germany中数组的第一项完全相同,我可以向我显示表ony 。 What iam doing wrong? 我做错了什么? https://scr.hu/eyjnr0
https://scr.hu/eyjnr0
function showCountriesList(resp) {
var url = 'https://restcountries.eu/rest/v2/name/';
var createdTable = createNewTable();
var countryName = $('#country-name').val();
resp.forEach(function(item) {
var row = document.createElement('tr');
row.innerHTML = `
<td><img style="width: 60px; height: 60px; object-fit: cover" src=${item.flag}></img></td>
<td>${item.name}</td>
<td>${item.capital}</td>
<td>${item.alpha2Code}</td>
<td>${item.timezones}</td>
`;
if (countryName === url.indexOf([item.name])) {
createdTable.appendChild(row); }
});
}
The information you provided is not clear enough to give a conclusive answer. 您提供的信息不够清晰,无法给出结论性的答案。
Your if statement is invalid and will always be false. 您的if语句无效,并且始终为false。 Assuming that the countryName variable holds a string and the indexOf function returns a number.
假设countryName变量包含一个字符串,并且indexOf函数返回一个数字。 Also your usage if the indexOf function is wrong as it expects a string not an array.
如果indexOf函数错误,因为它期望的是字符串而不是数组,因此也是您的用法。
if (countryName === url.indexOf([item.name])) {
createdTable.appendChild(row); }
I am assuming that the above code is trying to check whether the countryName value is the same as the one in the url. 我假设上面的代码正在尝试检查countryName值是否与url中的那个相同。
I suggest you try using the string function includes 我建议您尝试使用字符串函数包括
if( url.includes(countryName)) createdTable.appendChild(row);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.