JS学习-JavaScript 基本语法
Posted znapast
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS学习-JavaScript 基本语法相关的知识,希望对你有一定的参考价值。
1
关键字var用于定义局部变量,去掉关键字var则可以定义全局变量.
//局部变量1
var message = “hi”,
found = false,
age = 29;
//局部变量2
function test()
var message = “hi”; //local variable
test();
alert(message); //error!
//全局变量
function test()
message = “hi”; //global variable
test();
alert(message); //”hi”
2
JS有5种基本数据类型和一种复杂数据类型: Undefined, Null,Boolean, Number, 和 String,以及Object。使用typeof操作符可以得到变量的数据类型:
- “undefined” if the value is undefined
- “boolean” if the value is a Boolean
- “string” if the value is a string
- “number” if the value is a number
- “object” if the value is an object (other than a function) or null
- “function” if the value is a function
var message = “some string”;
alert(typeof message); //”string”
alert(typeof(message)); //”string”
alert(typeof 95); //”number”
var message;
alert(message == undefined); //true
var car = null;
alert(typeof car); //”object”
//undefined 类型继承自 null类型
alert(null == undefined); //true
var message = “Hello world!”;
var messageAsBoolean = Boolean(message);//true
var b1 = Boolean("")//false
var b2 = Boolean(0)//false
var b3 = Boolean(NaN)//false
var b4 = Boolean(1)//true
var b5 = Boolean(-1)//true
var b6 = Boolean(null)//false
var b7 = Boolean(undefined)//false
var b8 = Boolean(n/a);//true
//NaN不等于任何对象,包括NaN
alert(NaN == NaN); //false
var num1 = Number(“Hello world!”); //NaN
var num2 = Number(“”); //0
var num3 = Number(“000011”); //11
var num4 = Number(true); //1
var num1 = parseInt(”AF”, 16); //175
var num2 = parseInt(”AF”); //NaN
var num1 = parseFloat(“1234blue”); //1234 - integer
//十六进制数都会变为0
var num2 = parseFloat(“0xA”); //0
var num3 = parseFloat(“22.5”); //22.5
var num4 = parseFloat(“22.34.5”); //22.34
var num5 = parseFloat(“0908.5”); //908.5
var num6 = parseFloat(“3.125e7”); //31250000
var num = 10;
alert(num.toString()); //”10”
alert(num.toString(2)); //”1010”
alert(num.toString(8)); //”12”
alert(num.toString(10)); //”10”
alert(num.toString(16)); //”a”
3
Object对象实例有以下属性和方法:
- constructor :构造方法
- hasOwnProperty(propertyName) : 使用有指定的属性
- isProtypeOf(object): 是否是某个实例对象的原型
- propertyIsEnumerable(propertyName): 属性是否可枚举
- toLocaleString(): 转换为表示该对象的字符串
- valueOf(): 得到代表该对象的字符串或者数字或者布尔值
对象比较”==” 和“===”
var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different data types
var result1 = (“55” != 55); //false - equal because of conversion
var result2 = (“55” !== 55); //true - not equal because different data types
逗号操作符
var num1=1, num2=2, num3=3;
var num = (5, 1, 4, 8, 0); //num becomes 0
Javascript中没有块作用域的概念,在块内定义的变量在块之外同样有效,例如:
var count = 10;
for (var i=0; i < count; i++)
alert(i);
//i同样的有效
alert(i); //10
for-in 表达式用于遍历对象中的属性。如下实例遍历window 对象中的所有属性
for (var propName in window)
document.write(propName);
以上是关于JS学习-JavaScript 基本语法的主要内容,如果未能解决你的问题,请参考以下文章