JS对象属性和方法 函数编写 JSON操作 特殊操作说明

2017-05-31 22:21:00
admin
原创 1565
摘要:JS对象属性和方法 函数编写 JSON操作 特殊操作说明

一、JS对象属性和方法

1 JS中一切都是对象,字符串、数字、数组、日期,等等;

2 属性是与对象相关的值;
3 方法是能够在对象上执行的动作;

4 字符串属性:length,字符串方法:indexOf()、replace()、search();


二、函数编写

1 普通函数:function myFunction(var1,var2){ 代码段 }

2 带返回值:function myFunction(var1,var2){ 代码段 return ret; }

3 局部变量在函数运行后会被删除;


三、JSON操作

序列化:

var user = {name:'feinen', age:21};
console.log(user);
console.log(JSON.stringify(user));
输出:

Object {name: "feinen", age: 21}

{"name":"feinen","age":21}


序列化数组:

var cars=new Array();
cars[0]="Audi";
cars[1]="BMW";
cars[2]="Volvo";
console.log(cars);
console.log(JSON.stringify(cars));
输出:

(3) ["Audi", "BMW", "Volvo"]
["Audi","BMW","Volvo"]


序列化特殊处理:

var user;
console.log(JSON.stringify(user));
user = null;
console.log(JSON.stringify(user));
user = 21;
console.log(JSON.stringify(user));

var user = {name:'feinen', age:null, loc: undefined};
console.log(user);
console.log(JSON.stringify(user));
输出:

undefined

null

21

Object {name: "feinen", age: null, loc: undefined}
{"name":"feinen","age":null}


反序列化:

var user = '{"name":"feinen","age":null}';
console.log(JSON.parse(user));
user = null;
console.log(JSON.parse(user));
user = '';
console.log(JSON.parse(user));
user = '{';
console.log(JSON.parse(user));
user = undefined;
console.log(JSON.parse(user));
输出:

Object {name: "feinen", age: null}

null

Uncaught SyntaxError: Unexpected end of input


四、特殊操作说明

1 等于与全等于,全等于会比较类型:

var name = '5';
console.log(name == 5);
console.log(name === 5);
console.log(undefined == null)
console.log(undefined === null)

输出:

true

false

true

false


2 美元符号$可以用于变量或函数的申明,放置中间位置也可以,比如fei$nen:

1 用于申明变量 $var

2 用于申明函数 $func


3 取变量类型

var name = 'feinen';
console.log(typeof name); 输出string;


4 字符串连接,如下格式都可以

str + str

str + num

num + str


5 NaN或者Number.NaN

var num = Number.NaN;
console.log(num == num);
console.log(isNaN(num))
console.log(num);
console.log(typeof num);
输出:

false
true
NaN
number


6 比较运算符

6.1数字和字符串混合,比较运算符先把字符串转换为数字在比较:

console.log('1' > 0)
console.log('1' == 1)
console.log('1' < 2)
true

true

true

6.2字符串和字符串比较按字典顺序比较

6.3其中一个表达式为NaN,则返回false


7 比较运算null和undefined

var num = 99;
console.log(num > null);
console.log(num == null);
console.log(num < null);
console.log(num > undefined);
console.log(num == undefined);
console.log(num < undefined);
true

false

false

false

false

false


var num = ‘99’;
console.log(num > null);
console.log(num == null);
console.log(num < null);
console.log(num > undefined);
console.log(num == undefined);
console.log(num < undefined);
true

false

false

false

false

false


var num = 0;
console.log(num > null);
console.log(num == null);
console.log(num < null);

false

false

false


var num = -1;
console.log(num > null);
console.log(num == null);
console.log(num < null);

false

false

true

发表评论
评论通过审核之后才会显示。