console.log 打印函数定义以及函数预期输出
console.log prints function definition, along with function expected output
我写了下面的代码:
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()[= 的函数定义22=] 函数,而不是它的唯一结果。
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.
另请注意,向您不拥有的对象(尤其是本机对象)添加意想不到的功能被认为是不好的做法,并且该功能看起来毫无用处:您可以使用 join 和 line_arr.join(";")
.
我写了下面的代码:
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()[= 的函数定义22=] 函数,而不是它的唯一结果。
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.
另请注意,向您不拥有的对象(尤其是本机对象)添加意想不到的功能被认为是不好的做法,并且该功能看起来毫无用处:您可以使用 join 和 line_arr.join(";")
.