1、有一个三位数,被4除余2,被7除余3,被9除余5,将满足条件的数据存放在一个数组中并输出。
<script>
var arr = [];
for (var i = 100; i < 1000; i++) {
if (i % 4 == 2 && i % 7 == 3 && i % 9 == 5) {
arr.push(i)
}
}
console.log(arr);
</script>
2、定义一个数组var arr =[11,22,0,0,0,33,44,55,0],要去除数组中的0,并生成一个新的数组。
<script>
var arr = [11, 22, 0, 0, 0, 33, 44, 55, 0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
arr.splice(i, 1);
i--;
}
}
console.log(arr);
</script>
<script>
var arr = [11, 22, 0, 0, 0, 33, 44, 55, 0];
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
continue;
}
arr2.push(arr[i]);
}
console.log(arr2);
</script>
3、封装一个函数,返回一个数组中偶数的个数
<script>
function getCount(arr) {
var n = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
n++;
}
}
return n;
}
var arr = [22, 33, 44, 5, 66, 7, 8]
var n = getCount(arr);
console.log(n);
</script>
<script>
Array.prototype.evenCount = function () {
var n = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] % 2 == 0) {
n++;
}
}
return n;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var x = arr.evenCount();
console.log(x)
</script>
4.找字符串里面的最长的单词,例 good morning boy! 最长单词是morning
<script>
var str = "good morning boy!";
var arr = str.split(" ");
var max = arr[0].length;
var index = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > max) {
max = arr[i].length;
index = i;
}
}
console.log(max);
console.log(index);
console.log(arr[index]);
</script>
5、随机生成10个100以内的整数,然后将奇数和偶数分别存入到二个不同的数组中,并输出。
<script>
var arr1 = [];
var arr2 = [];
for (var i = 0; i < 10; i++) {
var x = parseInt(Math.random() * 100)
if (x % 2 == 0) {
arr2.push(x)
} else {
arr1.push(x)
}
}
console.log(arr1);
console.log(arr2);
</script>
6、一组蔬菜英文(Potato、Carrot、Onion、Aubergine、Celery、White Cabbage、 Cauliflower) 输出含有“o”或者含有“f”的单词
<script>
var arr = ["Potato", "Carrot", "Onion", "Aubergine", "Celery", "White Cabbage", "Cauliflower"]
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes("o") || arr[i].includes("f")) {
console.log(arr[i]);
}
}
</script>
7、数组中的每一位数字都增加50%,并返回一个新数组 var arr =[10,20,30];
<script>
var arr = [10, 20, 30];
var newArr = []
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i] * 1.5)
}
console.log(newArr);
<script>
var arr = [10, 20, 30];
var arr2 = arr.map(function (item) {
return item * 1.5;
})
console.log(arr2);
</script>