1、返回指定数组
var arr = []
function getArr(a) {
for(let i = 0; i < a; i++) {
arr.push(i + 1)
}
return arr
}
var result = getArr(9)
console.log(result);
< (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
2、返回a~b范围的数组
var arr = []
function newArr(a, b) {
for(let i = a; i < b; i++) {
arr.push(i)
}
return arr
}
console.log(newArr(3, 9));
< (6) [3, 4, 5, 6, 7, 8]
3、数组去重
1、for循环嵌套,利用splice去重
const ARR = [1, 2, 3, 4, 1, 2, 3, 5, 5, 1, 6, 7, 8, 9]
function newArr(ARR) {
for(let i = 0; i<ARR.length; i++){
for(let j = i+1; j<ARR.length; j++){
if(ARR[i] == ARR[j]){
ARR.splice(j, 1);
j--;
}
}
}
return ARR;
}
console.log(newArr(ARR))
< [1, 2, 3, 4, 5, 6, 7, 8, 9]
2、ES6中使用Set去重
// Set只有属性值,成员唯一值,可以转换成数组,进行去重、取交集、并集、差集等操作
var arr = [1, 2, 3, 4, 1, 2, 3, 5, 5, 1, 6, 7, 8, 9]
function newArr(arr) {
return Array.from(new Set (arr))
}
console.log(newArr(arr));
< [1, 2, 3, 4, 5, 6, 7, 8, 9]
4、数组求和
const ARR = [1, 3, 5]
function sumNum(ARR){
let num = 0
for(let i = 0; i<ARR.length; i++) {
num += ARR[i]
}
return num
}
console.log(sumNum(ARR));
< 9
5、数组排序
// 数组排序,由大到小
var arr1 = []
function newArr1(a, b) {
for(let i = a; i >= b; i--) {
arr1.push(i)
}
return arr1
}
console.log(newArr1(9, 3));
<(7) [9, 8, 7, 6, 5, 4, 3]
// 数组排序,由小到大
var arr2 = []
function newArr2(a, b) {
for(let i = b; i <= a; i++) {
arr2.push(i)
}
return arr2
}
console.log(newArr2(9, 3));
< (7) [3, 4, 5, 6, 7, 8, 9]