美文网首页
第22章 JS Math

第22章 JS Math

作者: kzc爱吃梨 | 来源:发表于2019-04-25 20:56 被阅读0次

1. 写一个函数,生成一个随机 IP 地址,一个合法的 IP 地址为 0.0.0.0~255.255.255.255。

function getRandIP(){
  //补全
}
var ip = getRandIP()
console.log(ip) // 10.234.121.45

我的回答:

function getRandIP(){
    let arr = [];
    for (let i = 0; i < 4; i++) {
        arr.push(Math.floor(Math.random() * 266));
    }
    return arr.join('.');
}
var ip = getRandIP()
console.log(ip)

2. 写一个函数,生成一个随机颜色字符串,合法的颜色为#000000~ #ffffff。

function getRandColor(){
}
var color = getRandColor()
console.log(color)   // #3e2f1b

我的回答:

function getRandColor(){
    var color = '#' ;
    var dict = '0123456789abcdef'
    for(var i=0; i<6; i++) {
        color += dict[Math.floor( Math.random()*16)]
    }
    return color;
}
var color = getRandColor()
console.log(color)   // #3e2f1b

3. 写一个函数,返回从min到max之间的 随机整数,包括min不包括max 。

我的回答:

function getRandomInt(min, max) {
  result = Math.floor(Math.random() * (max - min + 1)) + min;
  return result;
}
console.log(getRadom(min,max)); 

4. 写一个函数,生成一个长度为 n 的随机字符串,字符串字符的取值范围包括0到9,a到 z,A到Z。

function getRandStr(len){
  //补全函数
}
var str = getRandStr(10); // 0a3iJiRZap

我的回答:

function getRandStr(len){
  var dict = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
  var str ='';
  for (var i=0; i<len; i++) {
    var index = Math.floor(Math.random()*dict.length);
    str += dict[index];
  }
  return str
}
var str = getRandStr(10);
console.log(str);

5. 写一个函数,参数为时间对象毫秒数的字符串格式,返回值为字符串。假设参数为时间对象毫秒数t,根据t的时间分别返回如下字符串:

  • 刚刚( t 距当前时间不到1分钟时间间隔)
  • 3分钟前 (t距当前时间大于等于1分钟,小于1小时)
  • 8小时前 (t 距离当前时间大于等于1小时,小于24小时)
  • 3天前 (t 距离当前时间大于等于24小时,小于30天)
  • 2个月前 (t 距离当前时间大于等于30天小于12个月)
  • 8年前 (t 距离当前时间大于等于12个月)
function friendlyDate(time){
}
var str = friendlyDate( '1484286699422' ) //  1分钟前(以当前时间为准)
var str2 = friendlyDate('1483941245793') //4天前(以当前时间为准)

我的回答是:

function friendlyDate(time){
  var d = Date.now()-time;
  switch(true){
    case d<0:
      console.log('在未来');
      break;
    case d>=0&&d<(60*1000):
      console.log('刚刚');
      break;
    case d>=(60*1000)&&d<(60*60*1000):
      console.log('3分钟前');
      break;
    case d>=(60*60*1000)&&d<(24*60*60*1000):
      console.log('8小时前');
      break;
    case d>=(24*60*60*1000)&&d<(30*24*60*60*1000):
      console.log('3天前');
      break;
    case d>=(30*24*60*60*1000)&&d<(12*30*24*60*60*1000):
      console.log('2个月前');
      break;
    case d>=(365*24*60*60*1000):
      console.log('8年前');
      break;
  }
}
var str = friendlyDate( '1556116109419' ) //  刚刚

相关文章

网友评论

      本文标题:第22章 JS Math

      本文链接:https://www.haomeiwen.com/subject/hyazgqtx.html