js 没有contains方法?提示错误

JavaScript014

js 没有contains方法?提示错误,第1张

这个是jQuery的方法;

描述: 检查一个DOM元素是另一个DOM元素的后代。

jQuery.contains( container, contained )

container

类型: Element

DOM元素作为容器,可以包含其他元素

contained

类型: Element

DOM元素,可能被其他元素所包含

如果第二个参数所提供的DOM元素是第一个参数DOM元素的后裔,那么$.contains() 方法返回true,无论是直接的子元素或者是后代元素。否则,返回false。只支持 element 节点如果第二个参数是一个文本或注释节点,$.contains()将返回 false。

在java中一般有两种方法较常用,分别是contains(String str)和indexOf(String str)。

其中contains返回值为boolean类型,true为有,false为没有;而indexOf实际上是查找一个字符串在另一个字符串的位置的一个方法,且以匹配好的第一个字符为准;所以该方法的返回值为int类型,其中 -1表示未找到,其余都是能找到意思。所以一般来讲,java中的判断方式如下:

String str = "abcde"

//第一种方法

if (str.contains("b")) {

    System.out.println("yes")

} else {

    System.out.println("no")

}

//第二种方法

if (str.indexOf("bc") >= 0) {

    System.out.println(str.indexOf("bc"))

    System.out.println("yes")

} else {

    System.out.println("no")

}

而在js中较为常见方法为indexOf(),返回值同java一样,为最常用的方法;随后,ES6又提供了三种新方法。includes(),返回布尔值,表示是否找到了参数字符串;startsWith(),返回布尔值,表示参数字符串是否在源字符串的头部;endsWith(),返回布尔值,表示参数字符串是否在源字符串的尾部。

var s = 'Hello world!'

if(s.indexOf('world')>=0){

    console.log('true')

}

if(s.includes('o')){

    console.log('true')

}

if(s.startsWith('Hello')){

    console.log('true')

}

if(s.endsWith('!')){

    console.log('true')

}