增加in判断

This commit is contained in:
白茶清欢 2023-07-31 17:26:12 +08:00
parent d925a453be
commit eb97a0b352
2 changed files with 35 additions and 0 deletions

View File

@ -239,3 +239,33 @@ func (at *ArrayType) Unique() []interface{} {
} }
return []interface{}{} return []interface{}{}
} }
// In 查询一个值是否在列表里, 在的话, 返回首次出现的索引, 不在返回-1
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:28 2023/7/31
func (at *ArrayType) In(input interface{}) int {
for idx := 0; idx < len(at.convertResult); idx++ {
if nil == input {
if nil != at.convertResult[idx] {
continue
}
return idx
}
if at.convertResult[idx] == nil {
continue
}
if reflect.TypeOf(at.convertResult[idx]).String() != reflect.TypeOf(input).String() {
// 类型不同
continue
}
sourceByte, _ := json.Marshal(at.convertResult[idx])
inputByte, _ := json.Marshal(input)
if string(sourceByte) != string(inputByte) {
continue
}
return idx
}
return -1
}

View File

@ -24,4 +24,9 @@ func TestArray(t *testing.T) {
c := map[string]interface{}{"name": "de"} c := map[string]interface{}{"name": "de"}
fmt.Println(reflect.DeepEqual(b, c)) fmt.Println(reflect.DeepEqual(b, c))
fmt.Println(reflect.DeepEqual(a, b)) fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(Array(valInt).In("1"))
fmt.Println(Array(valInt).In(1))
fmt.Println(Array(valInt).In(2))
fmt.Println(Array(valInt).In(7))
fmt.Println(Array(valInt).In(20))
} }