JavaScript 中 startsWith() 方法的重要性是什么?
要了解一个字符串是否以特定字符或一个字符串开头,indexOf() 方法被用到了。但在高级应用程序中,这种方法已经过时了。因此,ES6 为我们提供了 startsWith() 方法来执行这些高级任务。
在下面的例子中,IndexOf() 方法被用来查找字符串是否以某个特定字符开头。
例子
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.indexOf('T') === 0);
</script>
</body>
</html>输出
true
在下面的例子中,startsWith() 方法被用来查找字符串是否以某个特定字符串开头,而不是 indexOf() 方法。
例子
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.startsWith('Tu'));
</script>
</body>
</html>输出
true
我们还可以发送一个 index 来搜索一个特定的字符串,无论它是否在该特定位置。
在下面的例子中,Indexes 被作为参数发送到 startsWith() 方法,以找出特定字符串是否在那些特定索引中。
例子
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.startsWith('Tut', 0));
document.write("</br>");
document.write(text.startsWith('ut', 1));
document.write("</br>");
document.write(text.startsWith('t', 2));
</script>
</body>
</html>输出
true true true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP