javascript - 给定一个无法解析为 int 的字符串,String.charAt() 返回什么?

标签 javascript string

'test'.charAt('not an integer');

此代码始终返回 't' ,我猜测当 charAt() 的参数时无法转换为整数,它只返回第一个字符。

但我似乎找不到这种行为的记录。我的假设正确吗?您能给我指出记录此行为的资源吗?

最佳答案

是的,它将返回第一个位置的字符。来自 ECMAScript 5 spec

Let position be ToInteger(pos).

在 ToInteger 规范中:

Let number be the result of calling ToNumber on the input argument.

在 ToNumber 规范中:

If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.

然后返回 ToInteger:

If number is NaN, return +0.

关于javascript - 给定一个无法解析为 int 的字符串,String.charAt() 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17429557/

相关文章:

string - 如何使用字段的 String() 打印结构?

javascript - 使用 jQuery/Javascript 单击时创建同一 Div 的多个随机实例?

javascript - React Native通过Navigator将用户输入数据传递给Tab Bar IOS中的组件

python - 我如何告诉 python 整个值是一个字符串?因为我的Excel公式中有撇号

c - 字符串到单个数字

python - Python 中的变量插值

string - 将字符串转换为 UTF-8 字节

javascript - Kendo DropdownList 服务器过滤添加参数

javascript - 有什么办法可以将Javascript中上传的附件文件发送到Python/Flask吗?

javascript - 无法检测JS中 'while loop'无限循环的原因