考虑以下字符串:
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 documentation ,endIndex
(第二个)参数是结束从源字符串提取的索引之前。
将结束索引放在所需内容之后的一个位置很有用,因为这样可以更轻松地进行数学计算。如果你想要从位置 i
开始的三个字符,你可以使用 source.slice(i, i+3)
。
关于javascript - 了解javascript中的切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674329/