San*_*nju 31 javascript jquery
此代码生成一个逗号分隔的字符串,以便为另一个页面的查询字符串提供id列表,但字符串末尾有一个额外的逗号.如何删除或避免使用额外的逗号?
<script type="text/javascript">
    $(document).ready(function() {
        $('td.title_listing :checkbox').change(function() {
            $('#cbSelectAll').attr('checked', false);
        });
    });
    function CotactSelected() {
        var n = $("td.title_listing input:checked");
        alert(n.length);
        var s = "";
        n.each(function() {
            s += $(this).val() + ",";
        });
        window.location = "/D_ContactSeller.aspx?property=" + s;
        alert(s);
    }
</script>
Sam*_*shi 91
使用 Array.join
var s = "";
n.each(function() {
    s += $(this).val() + ",";
});
变为:
var a = [];
n.each(function() {
    a.push($(this).val());
});
var s = a.join(', ');
Ama*_*osh 27
s = s.substring(0, s.length - 1);
CMS*_*CMS 13
您可以使用String.prototype.slice带负endSlice参数的方法:
n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"
或者您可以使用该$.map方法构建逗号分隔的字符串:
var s = n.map(function(){
  return $(this).val();
}).get().join();
alert(s);
您可以直接跳过添加它,而不是删除它:
var s = '';
n.each(function() {
   s += (s.length > 0 ? ',' : '') + $(this).val();
});
运用 substring
var strNumber = "3623,3635,";
document.write(strNumber.substring(0, strNumber.length - 1));运用 slice
document.write("3623,3635,".slice(0, -1));运用 map
var strNumber = "3623,3635,";
var arrData = strNumber.split(',');
document.write($.map(arrData, function(value, i) {
  return value != "" ? value : null;
}).join(','));<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>使用 Array.join
var strNumber = "3623,3635,";
var arrTemp = strNumber.split(',');
var arrData = [];
$.each(arrTemp, function(key, value) {
  //document.writeln(value);
  if (value != "")
    arrData.push(value);
});
document.write(arrData.join(', '));<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>