我在进行javascript编程时,因为需要判断数组对象是否包含某个元素,所以想到修改Array.prototype,添加contain方法,以模仿java中collection接口实现包含判断。因此我做了如下的工作:
Array.prototype.contain = function(item){
var flag =false;
for(index in this){
flag = (item==this[index])?true:false;
if(flag)break;
}
return flag;
}
var specified = ["Music","Shows","Movies"];
var a = "Music";
if(specified.contain(a)){
alert("in"); //run this line
}else{
alert("not");
}
alert(specified.length); //3for(var i = 0 ;i<specified.length;i++){
alert(specified[i]); //3 times
}
for(index in specified){
alert(specified[index]); //4 times,the last is the function 'contain'
}
但是这种方式对于要经常使用for( index in array)这种形式遍历数组反而是不利的(主要是担心同一个页面由不同的人在工作)。所以替代的方法就是:
function ArrayContain(array,item){
var flag =false;
for(index in array){
flag = (item==array[index])?true:false;
if(flag)break;
}
return flag;
}
使用一个额外的辅助函数,将数组和要判断的对象作为参数传递,尽管这不是我最初的想法。
json的遍历(key in json):
var specified = {x:"Music",
y:"Shows",
z:"Movies"};
for(key in specified){
alert("key is :" + key + " value is :" +specified[key]);//alert("key is :" + key + " value is :" +eval("specified."+key));also ok.
}
Array的遍历(index in array):
var specified = ["Music","Shows","Movies"];
for(index in specified){
var num = parseInt(index)+1;
alert("The no."+num+" is " + specified[index]);
}