JavaScript 如何计算数组元素的异或
在这篇文章中,我们给出了一个数组,并且任务是使用JavaScript找到数组元素的异或。有两种方法来解决这个问题,如下所述:
方法1: 它使用一种简单的方法通过索引号访问数组元素,并使用循环来找到数组元素值的异或。
示例: 这个示例使用一种简单的方法来找到数组元素的异或。
<!DOCTYPE html>
<html>
<head>
<title>
How to Find the XOR of Values
of an Array in JavaScript?
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>
How to Find the XOR of Values
of an Array in JavaScript?
</h3>
<h4>
----Given Array----<br>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</h4>
<button onclick="myGeeks()">Click</button>
<p id="gfg"></p>
<script>
function XOR(input)
{
if (toString.call(input) !== "[object Array]")
return false;
var total = Number(input[0]);
for(var i=1;i<input.length;i++) {
if(isNaN(input[i])){
continue;
}
total ^= Number(input[i]);
}
return total;
}
function myGeeks(item) {
document.getElementById("gfg").innerHTML
= "----XOR of Array----" + "<br>"
+ XOR([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
</script>
</body>
</html>
输出:
使用 reduce() 方法 : JavaScript 中的数组 reduce() 方法用于将数组减少为单个值,并对数组的每个值(从左到右)执行提供的函数,并将函数的返回值存储在累加器中。
语法:
array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )
示例: 这个示例使用数组的reduce()方法来使用JavaScript找到数组值的异或。
<!DOCTYPE html>
<html>
<head>
<title>
How to Find the XOR of Values
of an Array in JavaScript?
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>
How to Find the XOR of Values
of an Array in JavaScript?
</h3>
<h4>
----Given Array----<br>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</h4>
<button onclick="myGeeks()">
Click Here!
</button>
<br><br>
XOR: <span id="GFG"></span>
<script>
var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function ORofArray(XOR, num) {
return XOR ^ num;
}
function myGeeks(item) {
document.getElementById("GFG").innerHTML
= arr.reduce(ORofArray);
}
</script>
</body>
</html>
输出: