// 用户随机输入两个数,作为函数的两个形参,并求出两个数之间所有数的和
let readline = require("readline-sync"); console.log("请输入第一个数:"); let a = parseInt(readline.question("")); console.log("请输入第二个数:"); let b = parseInt(readline.question("")); function test(a,b){ let temp; if(a>b){ temp=a; a=b; b=temp; } let sum = 0;//用来求和 for( let i = a;i <= b;i++){ sum +=i; } return sum; } console.log("和为:",test(a,b));
// 用户定义数组的长度,然后手动输入一个数组,
// 针对这个数组求最大值和最小值,要求封装成一个函数
let readline = require("readline-sync"); console.log("请输入数组的长度:"); let lenght = parseInt(readline.question("")); let arr = []; let i,j; for(i =0;i<lenght;i++){ console.log(`请输入第${i+1}个数`); let num = parseInt(readline.question("")); arr[i] = num; } function test(now,func){ let str = []; for(i =0;i<arr.length;i++){ str[i] = arr[i] } console.log(str.sort(function(a,b){ return a-b;//升序 })); switch(func){ case 1: return str[0]; //找最小值数组的下标为0,就是第一个元素 break; case 2: return str[str.length-1];//找最大值数组的下标就是数组的长度-1,就是最后一位元素, break; } } console.log("该数组最小值为:",test(arr,1)); console.log("该数组最大值为:",test(arr,2)); console.log("该数组是:",arr);
// 对这个对象数组进行排序,首先按照年龄来排序,如果年龄相同,分数低的排在前面,
// 如果分数也相同,则学号低的排在前面
let i = [ {id:1,name:'张三',age:20,score:87}, {id:2,name:'李四',age:18,score:77}, {id:3,name:'王五',age:23,score:65}, {id:4,name:'赵六',age:25,score:87}, {id:5,name:'田七',age:27,score:82}, {id:6,name:'王八',age:21,score:74}, {id:7,name:'小明',age:19,score:91}, {id:8,name:'小红',age:28,score:92}, {id:9,name:'小李',age:20,score:78}, {id:10,name:'牛牛',age:18,score:87}, {id:11,name:'妞妞',age:23,score:65}, {id:12,name:'六九',age:20,score:82}, ]; i.sort(function(a,b){ if(a.age == b.age){ if(a.score == b.score){ return a.id - b.id; } else{ return a.score - b.score; } } else{ return a.age - b.age; } }); console.log(i);
// 用户随机输入一段英文语句,求出有多少单词及单词数量
let readline = require("readline-sync"); console.log("请输入英文语句:"); let str = readline.question(""); console.log("你的单词个数为:",word(str)); function word(word){ let arr = word.split(" "); console.log(arr); let n = 0; for(let i = 0;i<arr.length;i++){ if(arr[i] != ""){ n++; } } return n; }
// 用户输入一段英文,找出该段英文中 最长单词 是什么
let readline = require("readline-sync"); console.log("请输入英文语句:"); let str = readline.question(""); function longword(str){ let arr =str.split(" "); let max = arr[0].length; for(let i = 1;i<arr.length;i++){ if(arr[i].length > max){ max = arr[i].length; } } let arr1 = []; for(let j =0;j<arr.length;j++){ if(arr[j].length == max){ arr1.push(arr[j]); } } return arr1; } console.log(longword(str));
// 钱币格式转换函数,
// 一串数字,转换为带有逗号分隔符的形式
// 例如:12345678 12,345,678 从后面开始每三位以一个逗号隔开
let num = "1234566789900987654432321"; function change(num){ let str = ""; for(let i = num.length-1;i>=0;i--){ str +=num[num.length-1-i]; if(i%3==0 && i !=0){ str+=","; } } return str; } console.log(change(num));