我编写了以下代码:
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/