📜  如何使用 JavaScript 计算数组元素的异或?

📅  最后修改于: 2022-05-13 01:56:42.695000             🧑  作者: Mango

如何使用 JavaScript 计算数组元素的异或?

给定一个数组,任务是使用 JavaScript 查找 Array 元素的 XOR。有两种方法可以解决这个问题,下面将讨论:

简单方法:它使用一种简单的方法通过索引号访问数组元素,并使用循环通过 JavaScript 查找数组值的异或。

示例:此示例使用一种简单的方法来使用 JavaScript 查找 Array 元素的 XOR。

 
 
  
 
     
        How to Find the XOR of Values 
        of an Array in JavaScript? 
     
 
  
 
      
    

          GeeksForGeeks      

             

          How to Find the XOR of Values          of an Array in JavaScript?      

             

          ----Given Array----
          [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]      

                          

                                        

输出:

  • 在点击按钮之前:
  • 点击按钮后:

使用reduce()方法: JavaScript中的数组reduce()方法用于将数组缩减为单个值,并对数组的每个值(从左到右)和函数的返回值执行一个提供的函数存储在一个累加器中。

句法:

array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )

示例:此示例使用数组 reduce() 方法使用 JavaScript 查找 Array 值的 XOR。

 
 
  
 
     
        How to Find the XOR of Values 
        of an Array in JavaScript? 
     
 
  
 
      
    

          GeeksForGeeks      

             

          How to Find the XOR of Values          of an Array in JavaScript?      

             

          ----Given Array----
          [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]      

                          

             XOR:                                         

输出:

  • 在点击按钮之前:
  • 点击按钮后: