I have the following code written:
我写了以下代码:
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;
};
The above method is called using the following code:
使用以下代码调用上述方法:
_new_line_str = line_arr.toMyString();
console.log(_new_line_str);
But using console.log(_new_line_str); written above prints the result followed by function definition for toMyString() function, and not the only result from it.
但是使用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;
};
1 个解决方案
#1
3
Don't use for in
to iterate over elements of an array, you're listing the object properties, including the inherited ones (among them the function you added).
不要使用for来迭代数组的元素,你要列出对象属性,包括继承的属性(其中包括你添加的函数)。
Change
更改
for(var j in this) {
to
至
for(var j=0; j<this.length; j++) {
From the MDN, Array iteration and for...in:
从MDN,Array迭代和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.
数组索引只是具有整数名称的可枚举属性,并且与一般对象属性相同。无法保证for ... in将以任何特定顺序返回索引,并且它将返回所有可枚举属性,包括具有非整数名称和继承的属性。
Note also that it's considered bad practice to add unexpected functions to objects you don't own (especially native ones) and that this functions looks useless : you can get the same result using join with line_arr.join(";")
.
另请注意,将不需要的函数添加到您不拥有的对象(特别是本机函数)被认为是不好的做法,并且此函数看起来没用:您可以使用与line_arr.join(“;”)的连接获得相同的结果。
#1
3
Don't use for in
to iterate over elements of an array, you're listing the object properties, including the inherited ones (among them the function you added).
不要使用for来迭代数组的元素,你要列出对象属性,包括继承的属性(其中包括你添加的函数)。
Change
更改
for(var j in this) {
to
至
for(var j=0; j<this.length; j++) {
From the MDN, Array iteration and for...in:
从MDN,Array迭代和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.
数组索引只是具有整数名称的可枚举属性,并且与一般对象属性相同。无法保证for ... in将以任何特定顺序返回索引,并且它将返回所有可枚举属性,包括具有非整数名称和继承的属性。
Note also that it's considered bad practice to add unexpected functions to objects you don't own (especially native ones) and that this functions looks useless : you can get the same result using join with line_arr.join(";")
.
另请注意,将不需要的函数添加到您不拥有的对象(特别是本机函数)被认为是不好的做法,并且此函数看起来没用:您可以使用与line_arr.join(“;”)的连接获得相同的结果。