`.at(index)` 和 `.charAt(index)` 之间的区别。

huangapple go评论62阅读模式
英文:

Difference between .at(index) and .charAt(index)

问题

这两个函数之间的唯一区别是我在[文档][1]中找到的`.at()`接受负索引还有其他区别吗

  [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
英文:

What is the difference between the following two functions?

let str = 'hello world';
str.at(6) // w
str.charAt(6) // w

The only difference that I can find in the documentation is that .at() accepted negative indices, is there another difference?

答案1

得分: 1

这里有一些我能回忆起的事情:

  • 显然浏览器支持,at() 是较新的
  • 当超出范围时,at() 返回 undefinedcharAt() 返回空字符串
  • 负索引(你已经提到了)
英文:

There are few things I can recall:

  • obviously browser support, at() is newer
  • when out of range, at() returns undefined and charAt() returns an empty string
  • negative indices (already mentioned by you)

答案2

得分: 0

这两种方法都会返回一个新的字符串,其中包含位于指定偏移量位置的单个UTF-16编码字符。

区别在于 .at 允许使用负数,它是一个较新的特性,因此某些旧版本的引擎可能不支持它。

另一个区别是,如果作为参数提供的数字超出了字符串的长度,.at 将返回 undefined,而 .charAt 将返回一个空字符串。

你可以在这里找到更多信息(.at())和这里(.charAt())。

英文:

Both methods will return a new string consisting of a single UTF-16 encoded character located at the specified offset o the string.

The difference is that .at accepts negative numbers, and it is a much newer feature, so older versions of some engines might not support it.

Another difference is the default value returned if the number provided as a parameter exceeds the length of the string. .at will return undefined while .charAt will return an empty string.

You can find more information here (.at()) and here (.charAt())

huangapple
  • 本文由 发表于 2023年4月20日 00:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定