1、利用for循环向数组中写入数据1~10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [];
for (var i=0; i<=9; i++) {
arr[i] = i+1; //向数组中写入数据
}
console.log(arr);
</script>
</body>
</html>
2、将数组中大于10的数据写到一个新数组中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [2,0,6,1,77,0,52,0,25,7]; //原数组
var arr1 = []; //新数组
var j = 0; //定义新数组的初始长度
for (var i=0; i<arr.length; i++) {
if (arr[i] >= 10) {
arr1[j] = arr[i]; //满足条件的数据放入到新数组
j++; //下标+1
}
}
console.log(arr1);
</script>
</body>
</html>
3、将数组中不为0的数据放到新数组中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [2,0,6,1,77,0,52,0,25,7];
var arr1=[];
for (var i=0; i<arr.length; i++) {
if (arr[i]!=0) {
arr1[arr1.length] = arr[i]; //更为简便,用新数组的长度作为下标
}
}
console.log(arr1);
</script>
</body>
</html>
4、翻转数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 将元素组中的所有元素从后向前遍历,然后挨个放入新数组中
var arr = [12,"abc","无语",100,9]; //原数组
var arr1 = []; //新数组
for (var i=arr.length-1; i>-1; i--) {
arr1[arr1.length] = arr[i]; //将原数组的元素放入到新数组中
}
console.log(arr1); //[9, 100, "无语", "abc", 12]
</script>
</body>
</html>