一、数组调用
indexOf() 方法可返回数组中某个指定的元素位置。
该方法将从头到尾地检索数组,看它是否含有对应的元素。开始检索的位置在数组 start 处或数组的开头(没有指定 start参数时)。如果找到一个 item,则返回 item 的第一次出现的位置。
如果在数组中没找到指定元素则返回 -1。
//语法
// array.indexOf(item,start)
//item 必须 要查找的元素的位置,
//start 非必须可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。
let food= ["番茄", "胡萝卜", "排骨", "苹果"];
let a = food.indexOf("苹果");
console.log(a) // 3
let b= food.indexOf("香蕉");
console.log(b) // -1
二、字符串调用
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
区分大小写
如果要检索的字符串值没有出现,则该方法返回 -1。
//语法
//string.indexOf(value,start)
// value 必须 要查找的元素的位置
// start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string.length - 1。如省略该参数,则将从字符串的首字符开始检索。
let str="Hello world!";
console.log(str.indexOf("Hello"));//0
console.log(str.indexOf("World") );//-1
console.log(str.indexOf("world"));//6
三、应用例子
可以实现多项选择
<template>
<div class="biaoqian">
<button v-for="(item,index) in biaoqianList"
:key='index'
class="btn"
type="default"
size="mini"
:class="{'active': isChange.indexOf(index)!=-1}"
@click="clickBtn(index)">{{item}}</button>
</div>
</template>
export default{
data(){
return{
isChange:[], //多选
biaoqianList:['早餐','午餐','晚餐','宵夜'],
foodChose:[]
}
},
methods:{
clickBtn(index){
// 多选
if (this.isChange.indexOf(index) == -1) {
if(this.isChange.length == 4){
uni.showToast({
title:'最多选择四项',
icon:'none'
})
}else{
this.isChange.push(index);//选中添加到数组里
}
} else {
this.isChange.splice(this.isChange.indexOf(index), 1); //取消选中
}
console.log(this.isChange)
// let biaoqianList = []
// for(let index in this.isChange){ //biaoqianList里面的索引重新加入
// biaoqianList.push(this.biaoqianList[this.isChange[index]])
// }
},
}
}
<style lang="less">
.biaoqian{
display: flex;
justify-content: start;
align-items: center;
.active{
background-color: #76d2f4 ;
color: white;
}
.btn{
border:0.01px solid #76d2f4;
background-color:white ;
color: #76d2f4;
}
}
</style>