javascript检查是否设置了数组键

时间:2010-12-11 07:03:05

标签: javascript

var place = []

place[0] = "Sant Marti de Canals";
place[1] = "Catalonia";
place[3] = "";
place[4] = "Spain";

placeTitle = place.join(",");

目前的输出是“Sant Marti de Canals,Catalonia ,,,西班牙”

怎么可能是“Sant Marti de Canals,加泰罗尼亚,西班牙”

3 个答案:

答案 0 :(得分:3)

您还可以定义过滤功能,这在许多其他情况下都很有用。

Array.prototype.filter = function(p) {
    var a = [];
    p = p || function (x) {return x;}
    for (var i = 0; i<this.length; ++i) {
        if (p(this[i])) {
            a.push(this[i]);
        }
    }
    return a;
}

...

placeTitle = place.filter().join(', ');

答案 1 :(得分:2)

为此编写自己的代码可以提供帮助

var place = []

place[0] = "Sant Marti de Canals"; place[1] = "Catalonia"; place[3] = ""; place[4] = "Spain";

var placeTitle ='';
for(var test in place) {
    placeTitle += place[test]!=''?place[test]+',':'';
}
placeTitle = placeTitle.substr(0,placeTitle.length-1)

答案 2 :(得分:0)

placeCopy=[];
for(var i=0;i<place.length;i++){
  if(typeof place[i] != 'undefined' && place[i].length > 0){  
    placeCopy.push(place[i]);
  }
}
placeTitle = placeCopy.join(",");