Python同Java同Js语言语法区别之二判断字符串字典列表含有某个值的方法

判断字符串字典列表含有某个值的方法

前言

作为一枚测开工程师,需要的技能是全栈的,项目中,经常需要切换语言进行开发,语言用多了,难免会经常用混淆,故趁有空整理下这系列笔记“Python同Java同Js语言语法区别‘,希望对大家有用。

Python

对于列表、字符串或者字典都可以使用in来判断是否存在

#!/usr/bin/python
list1=["testxiaosheng"]
str1="testxiaosheng666"
dict1={"testxiaosheng":666}

if list1 and "testxiaosheng" in list1:
	print("list1有匹配值")
if str1 and "testxiaosheng" in str1:
	print("str11有匹配值")
if dict1 and "testxiaosheng" in dict1:
	print("dict1有匹配值")
if dict1 and  "testxiaosheng" in dict1.values():
	print("dict1 values有匹配值")

注意:首先需要判断None的情况,in字典时,默认是匹配字典的keys。等价于in dict.keys()

Java

字符串

使用contains或者indexOf

        String s1 = "ab";
        String s2 = "abandon";
//        if (  s1 != null  && s2 != null  && (s2.indexOf(s1)!=-1) ){ //indexOf不匹配返回-1
        if (  s1 != null  && s2 != null  && s2.contains(s1) ){
            System.out.println("存在");
        }
        else{
            System.out.println("不存在");
        }

数组

同样使用contains可以判断

        List<String> l1 =new ArrayList();
        l1.add("testxiaosheng");
        if (l1 !=null && l1.contains("testxiaosheng")){
            System.out.println("存在");
        }else {
            System.out.println("不存在");
        }

Map

可以使用containsKey()判断是否存在key,containsValue判断是否存在value

        Map<String,String> m1= new HashMap<String,String>();
        m1.put("testxiaosheng","666");
        if (m1 !=null && m1.containsKey("testxiaosheng")){
            System.out.println("key存在");
        }else {
            System.out.println("key不存在");
        }

Js

字符串

使用indexOf 查找,查找不到返回-1

var str1 = "testxiaosheng";
// var str1=null;
// var str1="testxiaosheng";

if( str1!==null&& str1!==undefined && str1.indexOf("test") != -1){
  console.log("存在");
}else{
   console.log("不存在");
}

数组

可以使用indexOf或者includes

// let arr=null;
// let arr 
let arr=[22,33] ;
if (arr!==null && arr!==undefined && arr.indexOf(22)!==-1   ){
// if (arr!==null && arr!==undefined && arr.includes(22)   ){ // 更简洁
   console.log("数组不为空")
}else {
   console.log("数组为空")
}

注意:使用 indexOf 需要判断是否为undefined以及null的情况

对象

可使用hasOwnProperty,或者in判断,建议使用in判断

// var object1;
//var object1 ={"test":666};
//var object1 ={"test":null};
var object1 ={"test":undefined};

if(object1!==null && object1!==undefined && "test" in object1){
//if(object1!==null && object1!==undefined &&  object1.hasOwnProperty("test")){

  console.log("object1存在key");
}else{
   console.log("object1为空");
}

参考文档:https://blog.csdn.net/Keep_Slience/article/details/125392133

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值