为什么字符串" nullfalse"出来输出?

时间:2017-05-26 10:55:25

标签: javascript unit-testing

buffer必须返回function,其返回String,我通过调用buffer('Hello')创建



/**
 * Function makeBuffer
 * @returns {String}
 */
function makeBuffer() {
    let str = '';
    return function(...rest) {
        if (rest.length === 0) {
            return str;
        }
        str += rest;
        str.toString();
    };
};
/**
 * Starting unit-test
 * @returns {String}
 */
;(function () {
  let buffer;
  beforeEach(function() {
    buffer = makeBuffer();
  });
  
  it("returns String", function() {
    buffer(null);
    buffer(false);
    assert.equal(buffer(), "nullfalse");
  });
})()


var buffer = makeBuffer();

buffer('Hello');
buffer(' my');
buffer(' world');

console.log(buffer());

<html>

<head>
  <meta charset="utf-8">
  <script src="https://js.cx/test/libs.js"></script>
</head>

<body>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

那是因为

[null].toString() == ""
[false].toString() == "false"

尝试

function makeBuffer() {
    let str = '';
    return function(...rest) {
        if (rest.length === 0) {
            return str;
        }
        str += rest.map(e => { return "" + e }).join("");
    };
};