1.JSON.stringify()
语法:
JSON.stringify(value)
作用:将 JavaScript 对象或数组转换为Json 字符串 ,与之相对的JSON.parse()则可以将JSON字符串转换为JSON对象,以便遍历处理时使用。
比如:
1.对象:
var student = new Object();
student.name = "Lanny";
student.age = "25";
student.location = "China";
var json = JSON.stringify(student);
alert(student);
结果:
{"name":"Lanny","age":"25","location":"China"}
2.数组:
var data = [{name:"Lanny",age:"25",location:"China"},
{name:"billy",age:"22",location:"USA"},
{name:"lina",age:"28",location:"Japan"}];
JSON.stringify(data);
结果:
'[{"name":"Lanny","age":"25","location":"China"},
{"name":"billy","age":"22","location":"USA"},
{"name":"lina","age":"28","location":"Japan"}]'
2.$.each()
多数是用来遍历数组和对象,比如在一个实际开发的例子中:
var cfg = {
type : 'point',
width : 300,
height : 300,
data:[
['中级' , .4 ,'#ff7676'],
['初级' , .2 ,'#ffa3a4', 0 ,'-60%'],
['高级' , .3 ,'#99c1ff', '50%' ,'-120%']
],
css : {
bottom:'20%'
},
center : true,
}
现在有一个函数实例需要用到这个数据:
var addComponnet = function(cfg, name ){
$.each(cfg.data, function(idx, item){
var point = $('<div class = "point point_'+idx+'">');
var name = $('<div class = "name">'+item[0]+'</div>');
var rate = $('<div class="per">'+ (item[1]*100)+'%</div>');
name.append(rate);
point.appeng(name);
/*后续代码*/
//this指向当前元素的值
//idx表示当前下标,obj表示当前元素的值
} )
}
3.$().each
经常用在dom处理上面,比如现在要同时处理很多类型为checkbox的input标签,用$().each就比较方便:
$(“input[name=’go’]”).each(function(i){
if($(this).attr(‘checked’)==true)
{
//处理代码
}
上例中回调函数为function的参数i为遍历索引。