javascript - console.log 打印函数定义以及函数预期输出

标签 javascript node.js console.log prototype-programming

我编写了以下代码:

Array.prototype.toMyString = function() {
    var _new_line_str = '';
    for(var j in this) {
        (this.length-1) != j 
            ? _new_line_str += this[j]+';' 
            : _new_line_str += this[j];
    }
    return _new_line_str;
};

使用以下代码调用上述方法:

_new_line_str = line_arr.toMyString();
console.log(_new_line_str);

但是使用上面编写的 console.log(_new_line_str); 会打印结果,后跟 toMyString() 函数的函数定义,而不是它的唯一结果。

Output:
this;is;a;result;of;above;code;;;;23function() {
    var _new_line_str = '';
    for(var j in this) {
        (this.length-1) != j 
            ? _new_line_str += this[j]+';' 
            : _new_line_str += this[j];
    }
    return _new_line_str;
};

最佳答案

不要使用 for in 来迭代数组的元素,您将列出对象属性,包括继承的属性(其中包括您添加的函数)。

改变

for(var j in this) {

for(var j=0; j<this.length; j++) {

来自 MDN,Array iteration and for...in :

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

另请注意,向您不拥有的对象(尤其是 native 对象)添加意外函数被认为是不好的做法,并且该函数看起来毫无用处:您可以使用 join 获得相同的结果。与line_arr.join(";")

关于javascript - console.log 打印函数定义以及函数预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424506/

相关文章:

javascript - NodeJS 和 Socket.IO

javascript - 如何在 Firefox 57.x 控制台中调查 reponseText/长文本?

javascript - console.log(variableName) 正在打印 ID 为变量名的标签的内容,而不是我的变量

javascript - javascript/nodeJs 中的两个递归函数和计算器错误。了解差异

javascript - Meteor 订阅事件/渲染

javascript - Web套接字性能

node.js - 如何停止 NodeJS 将 GET 请求打印到控制台

javascript - CoffeeScript 与 Node.js 不适用于类

node.js - 在 Ubuntu 13.10 上安装 Phonegap

node.js - 如何使用everest-js创建Note?