我想在我的浏览器<p>元素上打印出一些数组文本,这是我的代码,

时间:2016-12-31 02:18:11

标签: javascript arrays

<body>

<p id="id"></p>

<script>
    function StringBuilder() {
        this._Buffer = [];

        StringBuilder.prototype = {

            Constructor: StringBuilder,

            add: function (str) {
                this._Buffer.push(str);
            },

            toString: function () {
                return this._Buffer.join('');
            }
        }
    }

    var sb = new StringBuilder();
    sb.add = "obber";
    sb.add = "stadspolizie";

    var id = document.getElementById("id");
    id.innerText = sb.toString();


</script>

</body>
<!-- all I see on the screen is [onject Object] how can I display the text there? -->

1 个答案:

答案 0 :(得分:0)

首先,当add用作setter(函数调用)时,您正在使用method,如sb.add = "obber"; 。换句话说:

:此:

sb.add("obber");

应该是:

add

之后,如果您尝试运行该undefined方法,则会注意到function StringBuilder() { this._Buffer = []; } StringBuilder.prototype = { Constructor: StringBuilder, add: function(str) { this._Buffer.push(str); }, toString: function() { return this._Buffer.join(''); } }; var sb = new StringBuilder(); sb.add("obber"); sb.add("stadspolizie"); var id = document.getElementById("id"); id.innerText = sb.toString();方法为<p id="id"></p>。那是因为你需要在构造函数之外移动原型方法。

最后的例子:

{{1}}
{{1}}