英文:
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()
返回undefined
而charAt()
返回空字符串 - 负索引(你已经提到了)
英文:
There are few things I can recall:
- obviously browser support,
at()
is newer - when out of range,
at()
returnsundefined
andcharAt()
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论