简体   繁体   English

如何使用 JS endswith() 方法检查字符串变量是否以数组中的任何一项结尾?

[英]How to use the JS endswith() method to check if a string variable ends with any one item from an array?

I tried this however it didn't work.我试过这个但是没有用。

const tlds = [".com", ".net", ".it", ".edu", ".gov"]
ent/*ent is an existing variable in my code*/.endsWith(tlds)

Do I have to make it that it checks through each item in the array?我是否必须让它检查数组中的每个项目?

Yes, you have to make it so that it checks through each item in the array.是的,你必须让它检查数组中的每个项目。 You could make a for-loop to check all items in the array.您可以创建一个 for 循环来检查数组中的所有项目。 Here's my code.这是我的代码。

const tlds = [".com", ".net", ".it", ".edu", ".gov"]

function endsWith(string, end) {
  for (let i = 0; i < tlds.length; i++) {
    if (string.endsWith(end[i]) === true) return true
  }
  return false
}

endsWith(ent, tlds)

Hope this helps(;希望这可以帮助(;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM