内置对象之Math

2018-04-03  本文已影响0人  倾国倾城的小饼干

Math对象只提供了静态对的属性和方法,所以使用时不用实例化,比如数组和字符串有实例化,可以直接用Math。

属性

console.log(Math.PI)

方法

应用

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

function random(len){
    return min+Math.floor(Math.random()*(max-min))
}
  1. 写一个函数,返回从min都max之间的 随机整数,包括min包括max

function random(len){
    return min+Math.floor(Math.random()*(max+1-min))
}
  1. 写一个函数,生成一个长度为 n 的随机字符串,字符串字符的取值范围包括0到9,a到 z,A到Z

function getRandStr(len){
  var str1='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var str2='';
  for(var i=0;i<len;i++){
    str2+=str1[Math.floor(Math.random()*62)]
}
  return str2
}
var str = getRandStr(10);
console.log(str)
  1. 写一个函数,生成一个随机 IP 地址,一个合法的 IP 地址为 0.0.0.0~255.255.255.255

function randomStr(){
    var arr=[];
    for(var i=0;i<4;i++){
    var num=Math.floor(Math.random()*256);
    arr.push(num);

}
  return arr.join('.')
}
randomStr()
console.log(randomStr())
  1. 写一个函数,生成一个随机颜色字符串,合法的颜色为#000000~ #ffffff

function randomColor(){
  var str='0123456789abcdef';
  var arr=['#'];
  for(var i=0;i<6;i++){
       arr.push(str[Math.floor(Math.random()*16)]);
}
    return arr.join('')
}
var randomColor=randomColor()
console.log(randomColor)
上一篇下一篇

猜你喜欢

热点阅读