js实例--数值

进制转换:

 

  • 不要对数值直接操作;
  • 使用toString(n);
  • 八进制和十六进制还要自行连接'0','0x';

生成随机数:要生成n-m的随机数;

Math.floor(Math.random()*(m-n+1)) + n;

随机产生颜色:

  • RGB值:
function randomVal (val) {

	return Math.floor(Math.random()*val + 1);

}

function randomColor() {

	return 'rgb(' + randomVal(255) + ',' + randomVal(255) + ',' + randomVal(255) + ')';

}

  • 十六进制:
function randomVal (val) {

   var result =  Math.floor(Math.random()*val + 1);

   result = result.toString(16);

   if(result.length < 2){

   	result = '0' + result;

   }

   return result;

}

function randomColor() {

	return '#' + randomVal(255)  + randomVal(255)  + randomVal(255);

}

计算表格数字:

<table>

	<tr>

		<td>1</td>

		<td>2</td>

		<td>3</td>

	</tr>

	<tr>

		<td>1</td>

		<td>2</td>

		<td>3</td>

	</tr>

</table>

------------------------------------------------------------------

var sum = 0;

 var cells = document.querySelectorAll("td:nth-of-type(2)");

 for (var i = 0; i < cells.length ; ++i) {

 	sum += parseFloat(cells[i].firstChild.data);

 };

 console.log(sum);

角度弧度转换:

var radians = degrees * (Math.PI/180);

var degrees = radians * (180/Math.PI);

数值转换:

'1'       >>> 0: 1

1         >>> 0: 1

''        >>> 0: 0

undefined >>> 0: 0

null      >>> 0: 0

1.0∙∙∙01  >>> 0: 1

Compare to:



Number('1')      : 1

Number(1)        : 1

Number('')       : 0

Number(undefined): NaN

Number(null)     : 0

Number(1.0∙∙∙01) : 1.0∙∙∙01

  

 

你可能感兴趣的:(js)