四. js高级 Math函数,数组,表,字符串,常用接口

1.Math工具

//Math为js自带,不需要带入
console.log(Math.PI); //js中的圆周率

//js提供的随机函数  Math.random() --> [0,1)
console.log(Math.random());
//返回一个[start, end)范围的随机整数
function randon_int(start, end){
	var num = start + (end - start) * Math.random(); // num为小数
	//向下取整
	return Math.floor(num);
}
console.log(randon_int(0, 25));

//三角函数
//正弦,余弦,正弦
//单位为数学的弧度,不是度,方向为数学的正方向,逆时针方向
console.log(Math.sin(Math.PI / 4)); //sin 45
console.log(Math.cos(Math.PI / 6)); //cos 30
console.log(Math.tan(Math.PI / 6)); //tan 30

//[0-360]度   [0,2PI]弧度
//度转弧度 180 = PI   360 = 2PI
function degree_to_r(degree) {
	return (degree / 180) * Math.PI;
}
//弧度转度
function r_to_degree(r) {
	return (r / Math.PI) * 180;
}
console.log(degree_to_r(90));

//反三角函数
r = Math.asin(0.5);
console.log(r_to_degree(r));

r = Math.acos(0.5);
console.log(r_to_degree(r));

r = Math.atan(1);
console.log(r_to_degree(r));

//返回一个坐标对应的角度 (PI,PI]  Math.atan2
r = Math.atan2(1, 1);
console.log(r_to_degree(r));

//Math.sqrt开根号 给定一个数的正平方根
console.log(Math.sqrt(4))

//计算两点之前的距离
function vector_distance(lhs_x, lhs_y, rhs_x, rhs_y) {
	var len = (lhs_x - rhs_x) * (lhs_x - rhs_x) + (lhs_y - rhs_y) * (lhs_y - rhs_y);
	return Math.sqrt(len);
}
console.log(vector_distance(0,0,1,1));

2.数组高级使用

//数组高级使用
var arr = [1,2,3,4,5,6];
console.log(arr.length); //数组长度
//打印数组内容
for(var i = 0; i < arr.length; i++) {
	console.log(arr[i]);
}
//for eche
for(key in arr) {
	console.log(arr[key]);
}

arr.push(100); //增加一个元素 
for(key in arr) {
	console.log(arr[key]);
}

//查找对象在数组中对应的索引
var index = arr.indexOf(100);
console.log(index);

//删除数组中某个元素 splice(开始索引,要删除的个数)
arr.splice(2,1);
for(key in arr) {
	console.log(arr[key]);
}

//数组中的排序
arr = [1,8,5,4,5,3,5,0,5,1,9];
//数组的排序是快速排序
arr.sort(function(lhs, rhs) {
	if(lhs < rhs) {
		return -1;
	}else if(lhs > rhs){
		return 1;
	}else{
		return 0;
	}
});
console.log(arr);

//随机打乱一个数组
var random_arr = [1,2,3,4,5,6,7,8,9,0];
random_arr.sort(function(rhs, lhs) {
	if(Math.random() < 0.5) {
		return -1;
	}else{
		return 1;
	}
});
console.log(random_arr);

//随机抽取一个球
console.log(random_arr[0]);

3.表的高级使用

//表的高级使用
var student = {
	xiaoming : 4,
	xiaohong : 7,
	xiaoluo : 8
};
//遍历表
for(var key in student) {
	console.log(key, student[key]);
}
//删除表中的某一条数据
delete student["xiaohong"];
//遍历表
for(var key in student) {
	console.log(key, student[key]);
}

4.字符串高级

//字符串高级
var str = "hello,world!!"
console.log(str.length);//字符串长度
console.log(str.indexOf("wor"));//返回参数字符串在字符串所在第一次出现的位置,如果没有返回-1
//替换字符串
var tmpStr = str.replace("world","kkk");
console.log(str);//不在原来的字符串改,会重新生成一个字符串对象
console.log(tmpStr);
//字符串大小写转换  也会重新生成新的字符串
var tmpStr1 = str.toUpperCase();
console.log(tmpStr1);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值