Part 1: ES6 语法——For…of…循环(附首字母大写方法)
格式:
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const digit of digits) {
console.log(digit);
}
Tips:建议使用复数对象名称来表示多个值的集合。这样,循环该集合时,可以使用名称的单数版本来表示集合中的单个值。例如,for (const button of buttons) {…}
。
练习:
编写符合以下条件的 for…of 循环:
- 循环访问 days 数组中的每一天
- 将一天的首字母大写
- 将这一天输出到控制台中
代码应该将以下每天输出到控制台中:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
题目:
/*
* Programming Quiz: Writing a For...of Loop (1-4)
*/
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
// your code goes here
我的答案:
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
// my code goes here
function firstUpperCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}
for(const day of days){
console.log(firstUpperCase(day));
}
这里很简单,难在第一次写首字母转大写…代码是:
function firstUpperCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}