1. 遍历数组,只打印长度大于5的字符串
console.log("1. 打印长度大于5的字符串"); const words = ['apple', 'cat', 'javascript', 'dog', 'elephant', 'hi']; for (let i= 0; i< words.length; i++){ if(words[i].length > 5){ console.log(words[i]); } }
2. 计算数组中所有数字的总和,但只包括大于10的数字
console.log("\n2. 计算大于10的数字的总和"); const numbers = [5, 15, 3, 25, 8, 30]; let sum = 0; for(let i=0; i< numbers.length; i++){ if(numbers[i] > 10){ sum = sum + numbers[i]; } } console.log(sum);
3. 找出数组中最长的字符串
console.log("\n3. 找出数组中最长的字符串"); const fruits = ['apple', 'banana', 'kiwi', 'strawberry', 'orange']; let max = ''; for(let i=0; i< fruits.length; i++){ if(fruits[i].length > max.length){ max = fruits[i]; } } console.log(max);
4. 创建一个新数组,包含原数组中所有偶数索引的元素
console.log("\n4. 创建包含偶数索引元素的新数组"); const colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange']; let newColors = []; for(let i=0; i< colors.length; i+=2){ if( i % 2 === 0){ newColors.push(colors[i]); } } console.log(newColors);
5. 统计字符串中元音字母的数量
console.log("\n5. 统计字符串中元音字母的数量"); const text = "Hello, welcome to JavaScript world!"; let count = 0; for(let i=0; i< text.length; i++){ if(text[i] === 'a' || text[i] === 'e' || text[i] === 'i' || text[i] === 'o' || text[i] === 'u'){ count++; } } console.log(count);
6. 将数组中的字符串转换为大写,但只转换长度大于3的字符串
console.log("\n6. 将长度大于3的字符串转换为大写"); const animals = ['cat', 'elephant', 'dog', 'giraffe', 'ox']; for(let i = 0; i< animals.length; i++){ if(animals[i].length > 3){ animals[i] = animals[i].toUpperCase(); } else { continue; } } console.log(animals);
7. 找出数组中第一个长度大于5的字符串
console.log("\n7. 找出第一个长度大于5的字符串"); const cities = ['NY', 'London', 'Tokyo', 'San Francisco', 'LA']; for(let i=0; i< cities.length; i++){ if(cities[i].length > 5){ console.log(cities[i]); break; } }
8. 创建一个新数组,包含原数组中所有包含字母'a'的字符串
console.log("\n8. 创建包含字母'a'的字符串的新数组"); const foods = ['apple', 'banana', 'cherry', 'date', 'fig']; let newFoods = []; for(let i=0; i< foods.length; i++){ if(foods[i].includes('a')){ newFoods.push(foods[i]); } } console.log(newFoods);
9. 计算数组中数字的平均值,但排除小于0的数字
console.log("\n9. 计算数组中正数的平均值"); const values = [10, -5, 20, 0, 15, -10, 30]; let avg = 0; let sum1 = 0; let count1 = 0; for(let i = 0; i< values.length; i++){ if(values[i] > 0){ sum1 = sum1 + values[i]; count1++; } } avg = count1 > 0 ? sum1 / count1 : 0; console.log(avg);