Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript are strings arrays-like objects?

Tags:

javascript

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?

like image 488
user1941537 Avatar asked Jun 13 '26 02:06

user1941537


2 Answers

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(…).

like image 122
Bergi Avatar answered Jun 14 '26 15:06

Bergi


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
}
like image 41
Chocolord Avatar answered Jun 14 '26 16:06

Chocolord



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!