最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

In JavaScript are strings arrays-like objects? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Nov 17, 2021 at 7:21 drnugent 1,5459 silver badges23 bronze badges asked Aug 13, 2018 at 12:04 user1941537user1941537 6,67517 gold badges67 silver badges114 bronze badges 2
  • 6 No, in JS strings are primitives. In order to use the string methods, a temporary object is created. – Teemu Commented Aug 13, 2018 at 12:04
  • 1 Notice, that there are some methods in String.prototype too ... – Teemu Commented Aug 13, 2018 at 12:13
Add a comment  | 

3 Answers 3

Reset to default 13

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
}

In javaScript the string letters are get stored in the indexed manner,both primitive as well as the object type string get stored in the indexed value of the string reference name. Then a question come to mind that why we convert string to array in javaScript,well if we want to sort the letters we need sort method which javaScript array consist.String contain no sort method.Sting contain some property like length,but srting does not contain all the methods an Array contain. If we apply sort method in string it give an error that "stringName.sort is not a function".

发布评论

评论列表(0)

  1. 暂无评论