我不知道结束在 JavaScript 中像这样工作等等1111



const str = 'Do. Or do not. There is no try.';
console.log(str.endsWith('try', 30)); //true 
console.log(str.endsWith('try.', 30)); //false

有人能解释为什么在例子2中它是假的吗。我觉得和上面的差不多,一定还真的吗?

因为在endsWith((中,第二个参数是length。字符串

Do. Or do not. There is no try.

31个字符长,通过将长度参数设置为30,您只测试

Do. Or do not. There is no try

不以try.结束

正如Ian所说,您可以省略length参数来测试整个字符串:

const str = 'Do. Or do not. There is no try.';
console.log(str.endsWith('try'));  // false
console.log(str.endsWith('try.')); // true

这是因为y是第30个字符,在您指定的函数调用的length参数中,它应该测试字符串前30个字符的结尾。因此,它没有考虑.(它是第31个字符(。

您实际上只测试了以下文本:

Do。或者不要。没有尝试

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

相关内容

最新更新