判断数组中是否存在某一元素

## 方法

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
// 检查数组是否包含某个值的方法
public class TestArray {
    // 使用List
    public static boolean useList(String[] arr, String targetValue){
        return Arrays.asList(arr).contains(targetValue);
    }
    // 使用Set
    public static boolean useSet(String[] arr, String targetValue){
        Set<String> set = new HashSet<String>(Arrays.asList(arr));
        return set.contains(targetValue);
    }
    // 使用循环判断
    public static boolean useLoop(String[] arr, String targetValue){
        for(String s : arr){
            if(s.equals(targetValue))
                return true;
            }  
            return false;
        }
    // 查找有序数组中是否包含某个值的用法
    public static boolean useArraysBinarySearch(String[] arr, String targetValue){
        int a=Arrays.binarySearch(arr, targetValue);
        if(a > 0)
            return true;
        else
            return false;
    }
}
/*
 * 显然,使用一个简单的循环方法比使用任何集合都更加高效。许多开发人员为了方便,都使用第一种方法,但是他的效率也相对较低。因为将数组压入Collection类型中,首先要将数组元素遍历一遍,然后再使用集合类做其他操作。
 */
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript,我们可以使用indexOf()方法来判断数组中是否存在某个特定值。该方法返回索引值,如果值存在于数组中,则返回该值的第一个出现位置的索引。如果值不存在,则返回-1。 以下是一个示例代码片段,演示如何使用此方法进行数组搜索: var myArray = ['apple', 'banana', 'grape', 'orange']; if (myArray.indexOf('grape') !== -1) { console.log('Grape is found in the array.'); } else { console.log('Grape is not found in the array.'); } 在上面的代码,我们定义了一个数组myArray,并通过indexOf方法搜索特定值'grape'。如果'grape'存在于数组中,则if语句将返回true,因此将输出“Grape is found in the array”,否则输出“Grape is not found in the array”。 此方法还可以与JavaScript的其他条件语句一起使用。例如,您可以使用while循环来遍历整个数组,查找特定值的出现: var myArray = ['apple', 'banana', 'grape', 'orange']; var i = 0; while (i < myArray.length) { if (myArray[i] === 'grape') { console.log('Grape is found at index ' + i + ' in the array.'); break; } i++; } 在上面的代码,我们使用while循环遍历数组中的每个元素,并使用if语句查找'grape'的出现位置。如果找到该值,则break语句将退出循环,并输出找到该值的位置。如果未找到,则循环将继续执行,并在结束时输出未找到该值的消息。 总之,使用indexOf()方法可以很容易地在JavaScript查找数组中的特定值。您可以根据自己的需要使用它来编写各种逻辑应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值