javascript - 了解javascript中的切片

标签 javascript string

考虑以下字符串:

const str = "I am a good boy"

At, index 7 = g At, indedx 10 = d But when I use, splice method for strings, which accept two parameters ie start index, end index, so when I use

const result = str.slice(7, 10)
console.log(result)

我期待它返回 good 但它只返回 goo 为什么会这样,即使在索引 10 处,d 也存在?

根据 W3 学校

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the starting index (position), and the ending index (position).

最佳答案

来自 the MDN documentationendIndex(第二个)参数是结束从源字符串提取的索引之前

将结束索引放在所需内容之后的一个位置很有用,因为这样可以更轻松地进行数学计算。如果你想要从位置 i 开始的三个字符,你可以使用 source.slice(i, i+3)

关于javascript - 了解javascript中的切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674329/

相关文章:

arrays - 如何从字符串中随机选择一定数量的项目,以空格分隔?

Java 文字字符串 : wrong charset at runtime

javascript - 动态页面和类似 Facebook 的框的解决方法

python - 使用 Numba 时如何指定 'string' 数据类型?

javascript - 开 Jest 深方法 spy

javascript - 从 Knockout ViewModel 进行 jQuery DOM 操作 - 使用绑定(bind)处理程序?

c - "%s ", 字符串后不打印空格

java - 提取相同字符的2个字符之间的字符串

javascript - 纯 Javascript 作为 Angular 2 服务

javascript - 如何在 Internet Explorer 9 或 10 中安装 JavaScript?