Strings in JavaScript have a length property like arrays, but they don't have methods such as forEach or reduce.
Does this mean that strings are array-like objects?
The term "array-like" usually refers to an object having an integer-valued .length property and correspondingly many elements stored in integer-keyed properties, so that we can access them by index like an array. Strings certainly fulfill that requirement.
No, strings do not have all the methods that arrays have. They don't inherit from Array.prototype, they are not real arrays - they're just array-like. You can however trivially convert a string to an array, either by ….split('') or by Array.from(…).
According to the documentation these functions does not exist (Documentation).
But you can add functions to the String prototype
// forEach function
String.prototype.forEach = function (f) {
for (i=0; i < this.length; ++i) {
f(this[i]);
}
}
// reduce function
String.prototype.reduce = function (f, start) {
result = (start == undefined) ? null : start
for(i = 0; i < this.length; ++i) {
result += f(this[i])
}
return result
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With