Viewing ./ArraySum.html Filesize: 2.55Kb
<html>
<head>
<script type="text/javascript">

 
function flexisum(a){

/*    alert("a is "+a);
    var a = document.flex.array1.value;
    alert("a is "+a);
    
    var a = [1,2,3,4];
    alert("a is "+a);
    */

    
    var total=0;
    for(var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (!element) continue;  // Ignore null and undefined arguments

        // Try to convert the argument to a number n,
        // based on its type
        var n;
        switch(typeof element) {
        case "number":
        alert("You entered a number,GREAT! no conversion needed");
            n = element;                  // No conversion needed here
            break;
        case "object":
            if (element instanceof Array) // Recurse for arrays
                n = flexisum.apply(this, element);
            else n = element.valueOf();   // valueOf method for other objects
            break;
        case "function":
            n = element();  
            alert("You entered a function, Trying to invoke functions");
            break;
        case "string":
            n = parseFloat(element);     
            alert("You entered a string, Trying to parse strings");
            break;
        case "boolean":
            n = NaN;
            alert(" You entered boolean, Can't convert boolean values");
            break;
        }

        // If we got a valid number, add it to the total.
        if (typeof n == "number" && !isNaN(n)) total += n;
        // Otherwise report an error
        else throw new Error("sum(): can't convert " + element + " to number");
    }
    alert("This is the sum of all the elements you entered"+ total);
    return total;
}

//var a = [1,2,3,4];

//var b = flexisum(a);




</script> 
</head>

<body>
How do I read in this from the user? ASk Prof Rasala for ideas! <br>
After my meeting with Prof. I realised that a simple prompt can do.<br> However 
we should realise that this is not very user-friendly and <br>should
be used for testing purposes.
<script>     

    var sum  = new Array();
     sum[1]=prompt("Enter number 1:","");
     sum[2]=prompt("Enter number 2:","");
     sum[3]=prompt("Enter number 3:","");
     sum[4]=prompt("Enter number 4:","");
     sum[5]=prompt("Enter number 5:","");
    //We could have done some more checking to ensure that only int's are entered but that's not our focus
alert("Calling flexisum(sum), this function adds up all the elements in the array which you have created above");
flexisum(sum);
</script>
<!-- <form name="flex">
 <input type="text" name="array1">
 <input type="button" value="Add" onclick="flexisum(array1.value);">
</form>   -->

</body>
</html>