一、自定义函数连接字符串
效果:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串连接函数</title>
</head>
<body>
<script type="text/javascript">
// concatenate("love","i","you");
function concatenate(operator, operand1, operand2){
var res = "";
res += operand1;
res += ' ';
res += operator;
res += " ";
res += operand2;
console.log(res);
}
concatenate("love","i","you");
</script>
</body>
</html>
二、实现Math.floor以及Math.pow函数功能
参数及结果:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function fun1(num){
var res = parseInt(num);
//三目运算符,第三个条件不能为空,不然会报错
(res == num || res < 0)?--res:null;
// if(res == num || res < 0)
// --res;
//向下取整 函数
// var res = Math.floor(num);
//JS无法用typeof判断出int或浮点,他们都是Number类型,且typeof函数返回类型为字符串 "NUmber"等
// if(typeof(num) == float || typeof(num) == double)
// res = parseInt(num);
// else if(typeof(num) == int)
// res = parseInt(num)-1;
// if(res < 0)
// --res;
console.log(res);
}
function fun2(num, power){
//次方 函数
// console.log(Math.pow(num,power));
num = parseFloat(num);
var temp = num;
for(var i = 0; i < parseInt(power) - 1; i++)
num *= temp;
console.log(num);
}
fun1(-11.1);
fun2(2,10);
</script>
</body>
</html>
注意:
1、三目运算符 ?: 的第三个参数不能为空,否则报错。
2、JS无法用typeof区分int或浮点型变量,他们都是Number类型,且typeof函数返回类型为字符串 “NUmber”。对于这个问题,在后面的学习中了解到,可以使用constructor判断,它也可以区分Array与Object,因为其本质上是找该变量/对象的构造函数,所以判断时要判断是否为函数。例如:if(arr.constructor == Array) 不需要双引号。
3、次方 函数:console.log(Math.pow(num,power));