我在尝试创建一个javascript函数时遇到了很多困难,该函数将过滤所有国家/地区的名称并返回以元音开头的国家/地区。
这是我到目前为止所做的:
var countries = ["Lithuania", "Congo", "Micronesia, Federated States of", "Gabon", "United Arab Emirates", "Turkey", "Northern Mariana Islands", "Hungary", "France Metropolitan", "Virgin Islands (U.S.)", "Singapore", "Falkland Islands (Malvinas)", "Cyprus", "Rwanda", "Somalia", "Chile", "Libyan Arab Jamahiriya", "Uzbekistan", "Ghana", "Bahamas", "Austria", "Monaco", "Iceland", "Tajikistan", "Estonia", "France", "Central African Republic", "Martinique", "Mongolia", "Brunei Darussalam", "French Guiana", "Cape Verde", "Comoros", "Macedonia, The Former Yugoslav Republic of", "Antigua and Barbuda", "United States Minor Outlying Islands", "Bouvet Island", "Maldives", "Cocos (Keeling) Islands", "South Georgia and the South Sandwich Islands", "Jordan", "Bhutan", "Finland", "Luxembourg", "Vanuatu", "Uganda", "Thailand", "Liberia", "Ethiopia", "Suriname", "Korea, Democratic People's Republic of", "Niger", "Burkina Faso", "Italy", "Indonesia", "Nepal", "Mauritania", "Cameroon", "Fiji", "Solomon Islands", "Ireland", "Philippines", "Tuvalu", "Sudan", "Guadeloupe", "Venezuela", "Trinidad and Tobago", "Samoa", "Niue", "Papua New Guinea", "Hong Kong", "Burundi", "Virgin Islands (British)", "Uruguay", "Vietnam", "Oman", "Christmas Island", "Israel", "Montserrat", "Czech Republic", "Senegal", "Afghanistan", "Greenland", "Norway", "Eritrea", "Haiti", "Tunisia", "Swaziland", "Guinea-Bissau", "Botswana", "Greece", "Slovakia (Slovak Republic)", "Netherlands", "Jamaica", "St. Pierre and Miquelon", "Ecuador", "Morocco", "Grenada", "Poland", "Malaysia", "Mauritius", "Gambia", "Zimbabwe", "Bosnia and Herzegowina", "Malawi", "Puerto Rico", "United States", "Syrian Arab Republic", "Azerbaijan", "Cook Islands", "Cayman Islands", "Svalbard and Jan Mayen Islands", "Korea, Republic of", "Costa Rica", "Dominica", "Slovenia", "Australia", "Peru", "Albania", "Palau", "Netherlands Antilles", "Saudi Arabia", "Canada", "Moldova, Republic of", "Faroe Islands", "Heard and Mc Donald Islands", "Croatia (Hrvatska)", "Andorra", "Nicaragua", "Panama", "Tokelau", "South Africa", "Lesotho", "French Southern Territories", "Algeria", "Guinea", "Aruba", "Saint Lucia", "Togo", "Turks and Caicos Islands", "Yugoslavia", "Liechtenstein", "Latvia", "Kyrgyzstan", "Cuba", "Zambia", "Marshall Islands", "Mozambique", "Sierra Leon"];
function CountryFilter(input) {
for (i=0; i<=input.length; i++) {
if (input.charAt(0) === "a","e","i","o","u") {
return input;
}
}
}
document.write(CountryFilter(countries));
答案 0 :(得分:0)
var startsWithVowels = countries.filter(function(country) {
var firstLetter = country.charAt(0);
return firstLetter.match(/[aeiou]/i); // or firstLetter.match([AEIOU])
});
console.log(startsWithVowels);
/
- 标记正则表达式的开头
[aeiou]
- 如果字符为a
或e
或i
或o
或u
/
- 标记正则表达式的结尾
i
- 允许不区分大小写的标志。
在您的情况下不需要i
标记,因为每个国家/地区的第一个字符都是大写的,但您可能知道可能会遇到哪些数据。最好不要对数据做出假设。)
使用代码here
播放有关正则表达式的更多信息,请阅读文档here