Home > front end >  How do I add up the values ​in the array with the values ​outside the array?
How do I add up the values ​in the array with the values ​outside the array?

Time:01-03

i want to make function for get the winner with two input integer, this function must have result first input is the winner if value biggest than second input

function winner(a, b) {
    let result = []
    for (let i = 0; i < 3; i  ){
        if (a[i] > b[i]){
            result[0]  = 1
        }
        if (a[i] < b[i]){
            result[1]  = 1
        }
    }
    
    return result
}

if input a = 2 b = 3

output: 0,1

if input a = 5 b = 3

output: 1,1

CodePudding user response:

Why not return the result of the checks?

return [ (a > b),  (a < b)];

CodePudding user response:

Your question is not clear 1.a & b are numbers , they are not arrays 2.you cant iterate over a numbers 3.kindly improve your question

And if you want to compare 2 numbers You can also use "Math.max()"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

If u want to only compare 2 numbers,you can also write by using ternary operator

return a > b ? [1,1] : [0,1]

CodePudding user response:

I am assuming that a and b are arrays.

And that the example is a array of a = [2,5],b = [3,3] and so a wins once and b wins once. If you get NaN as a result it is because you are adding 1 to a empty array ,result.

So the solution would be to change

let result = [];

to

let result = [0,0];

also you need to make the for loop for the length of the array so the 3 in the for loop needs to be changed to

for(let i = 0;i<a.length;i  ){
  • Related