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.
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;
};
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).
Change
for(var j in this) {
to
for(var j=0; j<this.length; j++) {
From the 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.
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(";")
.