JS创建一个数组1.求和 2.求平均值 3.最大值 4.最小值 5.数组逆序 6.数组去重 0.退出

rs = require("readline-sync");
let arr = [];
console.log("请输入数组的长度:");
let arr_length = rs.question() - 0;
console.log("请添加数组中的元素:");
for (let index = 0; index < arr_length; index++) {
    arr[index] = rs.question() - 0;
}
console.log("创建的数组为:");
console.log(arr);
console.log("请对数组选择操作:1.求和 2.求平均值 3.最大值 4.最小值 5.数组逆序 6.数组去重 0.退出");
let option = rs.question() - 0;
let sum = 0,  arr_max = arr[0], arr_min = arr[0];
arr.forEach(element => {
    sum += element;
});
switch (option) {
    case 1:
        console.log(sum);
        break;
    case 2:
        console.log(sum / arr.length);
        break;
    case 3:
    for (let index = 1; index < arr.length; index++) {
        if (arr_max < arr[index]) {
            arr_max = arr[index];
        }
    }
        // for (let index = 1; index < arr.length - 1; index++) {
        //     arr_max = arr[index + 1] = Math.max(arr[index], arr[index + 1]);
        // }
        console.log(arr_max);
        break;
    case 4:
    for (let index = 1; index < arr.length; index++) {
        if (arr_min > arr[index]) {
            arr_min = arr[index];
        }
    }
        // for (let index = 1; index < arr.length - 1; index++) {
        //     arr_min = arr[index + 1] = Math.min(arr[index], arr[index + 1]);
        // }
        console.log(arr_min);
        break;
    case 5:
        arr.reverse();
        // for (let index = 0; index <arr.length/2; index++) {
        //     let t=arr[index];
        //     arr[index]=arr[arr.length-1-index];
        //     arr[arr.length-1-index]=t;
        //  }
        console.log(arr);
        break;
    case 6:
        let arr_new = new Set(arr);
        // let arr_new = [], index_new = 0;
        //    for (let i = 0; i < arr.length-1; i++) {
        //       for (let j = i+1; j < arr.length; j++) {
        //          if (arr[i]==arr[j]) {
        //         delete arr[i];
        //          }
        //       }
        //    }
        //    arr.forEach(element => {
        //        if (typeof element=="number") {
        //            arr_new[index_new]=element;
        //            index_new++;
        //        }
        //    });
        console.log(arr_new);
        break;
    case 0:
        break;
    default:
        console.log("输入有误,程序结束");
        break;
}
console.log(1+undefined)
上一篇:【原创】leetCodeOj --- Sliding Window Maximum 解题报告


下一篇:SQL的IN, SOME,ANY,IN