一、内置函数
1、parseInt()函数:将一个字符串按制定的进制转换为一个整数;
2、parseFloat()函数:将一个字符串转换为对应的浮点数数;
3、isNaN() (即is Not a Number) 函数:用于检测一个变量或一个字符串是否为NaN;如果是返回true,否则返回false。
4、案例:
模拟一个简单的计算器:
<body>
第一个数:<input type="text" id="one" /><br />
第二个数:<input type="text" id="two" /><br />
运算方式:<input type="button" name="" id="jiafa" value="+" onclick="cal_1('+')" />
<input type="button" name="" id="jianfa" value="-" onclick="cal_1('-')" />
<input type="button" name="" id="chengfa" value="*" onclick="cal_1('*')" />
<input type="button" name="" id="chufa" value="/" onclick="cal_1('/')" /><br />
运算结果:<input type="text" name="result" id="result" value=""/>
<script type="text/javascript">
function cal_1(y) {
var one = document.getElementById("one").value
var two = document.getElementById("two").value
var result = 0
//实现两个数相加
//获取文本框的值
if(y=="+") {
result = parseFloat(one) + parseFloat(two)
}else if(y=="-") {
result = parseFloat(one) - parseFloat(two)
}else if(y=="*") {
result = parseFloat(one) * parseFloat(two)
}else if(y=="/") {
result = parseFloat(one) / parseFloat(two)
}
document.getElementById("result").value = result
}
</script>
</body>
二、面向对象
<script type="text/javascript">
//自定义对象的创建
//使用Object创建对象
var student = new Object()
console.log(student)
//给对象student添加属性stuId,stuName,className
student.stuId = "1001"
student.stuName = "张三"
student.className = "移动2班"
student.sayHallo=function(){
console.log("大家好")
}
//对象名,函数名()实现函数的调用
//student.sayHello()
console.log(student.stuID)
//使用function创建一个对象
function teacher(tid,tname) {
//this表示当前对象
this.tid=tid//教师编号
this.tname=tname//教师姓名
this.eat=function(){
console.log("吃饭")//教师行为
}
}
var t1=new teacher("1","李")
//使用t1来访问属性核函数
//调用函数
console.log(t1.tid,t1.tname)
</script>
字符串对象:
<script type="text/javascript">
//字符串对象
var str="Hello World!"
console.log(str.length)//length用来获取字符串的长度
console.log(str.charAt(2))
/*function test(){
console.log("aa")
}
console.log(test())*/
console.log(str.indexOf("1"))
console.log(str.indexOf("b"))
//判断是否包含某个字符
console.log(str.substring(0,5))//[0,5)
//substr():第一个函数指的是索引,第二个函数指的是截取的字符串的长度
console.log(str.substr(1,2))
</script>