一、js三种输出方式
1,使用alert() 弹出警告框。
<html>
<script>
alert('我是弹窗');
</script>
</html>
2,使用 document.write() 方法将内容写到 HTML 文档中。
3,使用 console.log() 写入到浏览器的控制台
<html>
<script>
document.write("123");
console.log("123");
console.warn("warning");
console.error("error");
</script>
</html>
二、访问对象属性和方法
对象名.属性名、对象名["属性名“]、对象名.函数名()
<html>
<script>
var person={
name:"007",
age:"999",
namefunction:function()
{
return this.name;
},
agefunction:function()
{
return this.age;
}
}
document.write(person.name+" "+person.age+" "+person.namefunction()+" "+person.agefunction()+" ");
document.write(person["name"]);
</script>
</html>
三、变量作用域
1,如果变量在函数内没有声明(没有使用 var 关键字),该变量为全局变量,如果在函数中使用var声明变量了,则为函数的局部变量。
// 此处可调用 carName 变量
function myFunction() {
carName = "Volvo";
// 此处可调用 carName 变量
}
2,使用window可以访问html里面所以的变量
在 HTML 中, 全局变量是 window 对象: 所有数据变量都属于 window 对象。
//此处可使用 window.carName
function myFunction() {
carName = "Volvo";
}
四、js事件
1,在button按钮中加入onclick属性运行一段js代码
<html>
<button onclick="document.write(Date())">
点我查看时间
</button>
</html>
五、For in循环遍历数组或者对象的属性
语法:
for (变量 in 对象)
{
在此执行代码
}
遍历对象的属性和方法(推荐遍历对象总是使用 hasOwnProperty 方法, 这将会避免原型对象扩展带来的干扰):
<html>
<script>
var x;
var person={
name:"007",
age:"999",
namefunction:function()
{
return this.name;
},
agefunction:function()
{
return this.age;
}
}
for(x in person){
document.write(person[x]+" ");
}
</script>
</html>
遍历数组:
<html>
<script>
var x;
var person=[1,2,3]
for(x in person){
document.write(person[x]+" ");
}
</script>
</html>
六、js的typeof
<html>
<script>
var x;
var person1=[1,2,3];
for(x in person){
document.write(person[x]+" ");
}
var person={
name:"007",
age:"999",
namefunction:function()
{
return this.name;
},
agefunction:function()
{
return this.age;
}
}
document.write(typeof person+"<br/>");
document.write(typeof person1+"<br/>");
document.write(typeof x);
</script>
</html>
注意:对象和数组的typeof都显示是object
原因:在JavaScript中所有数据类型严格意义上都是对象,但实际使用中我们还是有类型之分,如果要判断一个变量是数组还是对象使用typeof搞不定,因为它全都返回object
因此,我们只能放弃这种方法,要判断是数组或者对象有三种方法
第一,使用typeof加length属性
数组有length属性,object没有,而typeof数组与对象都返回object,所以我们可以这么判断
var getDataType = function (o) {
if (typeof o == 'object' && o) {
if(typeof o.length === 'number'){
return 'Array';
}else{
return 'Object';
}
} else {
return 'param is not object type';
}
};
document.write(typeof person+"<br/>");
document.write(typeof person1+"<br/>");
document.write(getDataType(person1)+"<br/>");
document.write(typeof x);
第二,使用instanceof
instanceof可以判断一个变量是不是数组(返回ture或者false)
document.write(typeof person+"<br/>");
document.write(typeof person1+"<br/>");
document.write(getDataType(person1)+"<br/>");
document.write(person1 instanceof(Array));
document.write(typeof x);
第三,使用constructor
constructor 属性返回所有 JavaScript 变量的构造函数。
document.write(person1.constructor)