[英]Create and array, then loop to find i then alert username
Create an array and fill it with at least six usernames (ie “Sophia”, “Gabriel”, …) then loop through them with a for loop. 创建一个数组,并使用至少六个用户名(即“ Sophia”,“ Gabriel”,…)填充它,然后使用for循环遍历它们。 If a username contains the letter “i” then alert the username. 如果用户名包含字母“ i”,则提醒用户名。
I have tried to make an array and create and "if" statement, then I want to make an alert. 我试图制作一个数组并创建和“ if”语句,然后我想发出警报。 I know I am missing something, but I can't figure out what. 我知道我缺少什么,但我不知道是什么。
let userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
if(userNames.includes('i')){
window.alert(userNames);
}
I would like there to be a window alert with the name "mike" 我希望有一个窗口警报,名称为“ mike”
Use a for loop if you want to return the index value of the array. 如果要返回数组的索引值,请使用for循环。 In this case we treat the letter i as a regular expression by placing it between two forward slashes, and try to match that string in each array value. 在这种情况下,我们通过将字母i放在两个正斜杠之间将其视为正则表达式,并尝试在每个数组值中匹配该字符串。 It then alerts you with the entire value (mike( 然后,它会以整个值(麦克(
let userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john']; for(let i = 0; i < userNames.length; i++) { if(userNames[i].match(/i/)) { window.alert(userNames[i]); } }
That's not how includes works... for example: 那不是include的工作原理...例如:
const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john'];
console.log(userNames.includes('mike')) // true
console.log(userNames.includes('i')) // false
To get what you want you can do something like this: 要获得所需的内容,可以执行以下操作:
const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john']; userNames.forEach(name => { if(name.includes('i')) { console.log(name) } })
Iterate over the array with forEach
then match it against a regular expression: 使用forEach
遍历数组,然后将其与正则表达式匹配:
const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john']; const regex = /i/; userNames.forEach(name => { if (name.match(regex)) { alert(name); } })
Or you could use includes
: 或者您可以使用includes
:
const userNames = ['rachel', 'greg', 'mike', 'adam', 'susan', 'john']; userNames.forEach(name => { if (name.includes("i")) { alert(name); } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.