该代码如何自动添加城市名称后的逗号?

时间:2014-04-17 07:55:58

标签: jquery

var arr = [];
$('#inputs input').change(function() {
    if (this.checked) {
        arr.push(this.value);
    }
    else {
        arr.splice(arr.indexOf(this.value), 1);
    }
    $('#target').val(arr + '');
});
<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <meta charset=utf-8 />
        <title>JS Bin</title>
    </head>

逗号如何在文本框中自动显示?并且在代码中它不打算打印

1 个答案:

答案 0 :(得分:2)

我认为它是Array对象的隐式toString方法,当arr与最后一行的emtpy字符串连接(如此隐式转换)时调用

例如

console.log([1,2,3].toString()) // This will return "1,2,3"
console.log([1,2,3]+'') // This will return "1,2,3" too !