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

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

一、JS对象属性和方法

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

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

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


二、函数编写

1、无返回值函数:function myFunction(var1,var2) { code; }

2、有返回值函数:function myFunction(var1,var2) { code; return ret; }

3、局部变量通过var关键字申明,不使用var关键字则为全局变量;


三、JSON操作

字典序列化

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


数组序列化

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


序列化特详解:

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

SyntaxError: Unexpected end of input


四、特殊操作说明

取变量类型:

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

输出:

string


比较运算符:

1、字符串和数字比较,字符串自动转为数字;

2、字符串和字符串按照字典顺序比较;

3、其中一个表达式为NaN,返回false;


全等于还会比较类型:

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

输出:

true

false

true

false


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


比较运算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

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