Blogger Information
Blog 28
fans 0
comment 0
visits 11630
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用Class类实现随机数生成并排列及简易计算
子墨吖ฅฅ
Original
348 people have browsed it
  1. // 使用class类实现随机数生成并排列及简易计算
  2. class Rndnumber {
  3. constructor(arr,num) {
  4. this.arr = arr
  5. this.num = num
  6. }
  7. getRandomArrayValue() {
  8. const newArr = []
  9. for(let i = 0; i < this.num; i ++){
  10. // Math.random() 默认取值范围 0 - 1
  11. // (this.arr.length - 1) 当前数组长度 - 1
  12. const random = Math.ceil((Math.random() * (this.arr.length - 1)));
  13. // splice截取数组内容 返回的是一个截取的数组
  14. // 取出截取数组的数据 存入新创建的数组
  15. newArr.push(this.arr.splice(random,1)[0])
  16. }
  17. return newArr
  18. }
  19. static arr = [0,1,2,3,4,5,6,7,8,9]
  20. }
  21. class Combination extends Rndnumber{
  22. constructor(arr,whether) {
  23. super(arr);
  24. this.whether = whether;
  25. }
  26. //数组排列方法
  27. arraySort(){
  28. if(this.whether === 0){
  29. return this.arr;
  30. }
  31. return this.arr.sort()
  32. }
  33. }
  34. class Calculator {
  35. constructor(arr,isMethod) {
  36. this.arr = arr;
  37. this.isMethod = isMethod
  38. }
  39. calculationData(){
  40. // 保存this 防止this指向被改变
  41. const _this = this;
  42. // 返回处理后的数组内容
  43. return this.arr.reduce((last,first)=>{
  44. switch (true){
  45. case _this.isMethod === '+' :
  46. return last + first;
  47. case _this.isMethod === '-' :
  48. return last - first;
  49. default :
  50. return last * first;
  51. }
  52. })
  53. }
  54. }
  55. //生成n个随机数
  56. const rndnumber = new Rndnumber(Rndnumber.arr,5)
  57. const randomArr = rndnumber.getRandomArrayValue();
  58. console.log('随机取数组内容 返回一个数组')
  59. console.log(randomArr)
  60. console.log('---------------')
  61. //数组是否排列 1===排列 0===原值返回
  62. const combination = new Combination(randomArr,1)
  63. //调用子类Combination的数组排列方法
  64. const sortArr = combination.arraySort();
  65. console.log('数组由小到大进行排列如下')
  66. console.log(sortArr)
  67. /**
  68. * 计算数组内的数据
  69. * (isMethod值默认为*)
  70. * + : 为数组内数据相加
  71. * - :数组内数据相减
  72. * * :数组内数组相乘
  73. */
  74. const calculator = new Calculator(sortArr,"-")
  75. const operation = calculator.calculationData();
  76. console.log('上述数组内容数据计算结果如下')
  77. console.log(operation)

运行图

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post