张映 发表于 2014-02-10
js数据格式和json数据格式,各有各的用处,就个人而言,json更好用一点,js自身的数组和对像限制比较多。
以js的数组举例:
- var a = ['1'];
- a[5] = 52;
- a.length //这儿的结果是6,也就是说,中间的key会自动补全,而值呢,是undefined
一,添加和删除
1,一维数组
- test = {}; //空json对像
- test['firstname'] = "tank"; //添加二个元素
- test['lastname'] = "zhang";
- console.log(test); //查看
- delete test['lastname']; //删除json中的某个元素
- console.log(test);
2,二维数组
- test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}];
- add = {"name":"may"};
- test1.push(add); //添加一个元素
- console.log(test1);
- delete test1[2]; //删除一个元素
- console.log(test1);
二,排序
1,一维数组
- test = ["100","23","325"]; //定义个数组
- function sortNumber(a,b) //定义排序方法
- {
- return a - b
- }
- test1_sort=test.sort(sortNumber);
- console.log(test1_sort);
2,二维数组
- test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}];
- sort_by = function(field, reverse, primer){ //定义排序方法
- var key = primer ?
- function(x) {return primer(x[field])} :
- function(x) {return x[field]};
- reverse = [-1, 1][+!!reverse];
- return function (a, b) {
- return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
- }
- }
- test1_sort=test1.sort(sort_by('total', true, parseInt)); //根据total,升序排
- console.log(test1_sort);
- test1_sort=test1.sort(sort_by('name', false, '')); //根据name,倒序排
- console.log(test1_sort);
别看是小问题,但是如果长时间不用,也会生疏,或者忘了。