JavaScript with Statement Example


with statement : establishes the default object for statements

The with statement is commonly used to shorten the amount of code.

Rewrite the example to use the with statement

with(Math)
{
    document.writeln("Math.PI = " + PI + "");
    //Output : Math.PI = 3.141592653589793
    
    //Math.round(x) returns the value of x rounded to its nearest integer
    document.writeln("Math.round(96.521) = " + round(96.521) + "");
    //Output : Math.round(96.521) = 97
    
    //Math.pow(x, y) returns the value of x to the power of y
    document.writeln("Math.pow(2,10) = " + pow(2,10) + "");
    //Output : Math.pow(2,10) = 1024
    
    //Math.sqrt(x) returns the square root of x
    document.writeln("Math.sqrt(16) = " + sqrt(16) + "");
    //Output : Math.sqrt(16) = 4
    
    //Math.abs(x) returns the absolute (positive) value of x
    document.writeln("Math.abs(-17.1) = " + abs(-17.1) + "");
    //Output : Math.abs(-17.1) = 17.1
    
    //Math.ceil(x) returns the value of x rounded "up" to its nearest integer
    document.writeln("Math.ceil(17.1) = " + ceil(17.1) + "");
    //Output : Math.ceil(17.1) = 18
    
    //Math.floor(x) returns the value of x rounded "down" to its nearest integer
    document.writeln("Math.floor(17.1) = " + floor(17.1) + "");
    //Output : Math.floor(17.1) = 17
    
    //Math.min() can be used to find the lowest value in a list of arguments
    document.writeln("Math.min(17,65,-10) = " + min(17,65,-10) + "");
    //Output : Math.min(17,65,-10) = -10
    
    //Math.max() can be used to find the highest value in a list of arguments
    document.writeln("Math.max(17,65,-10) = " + max(17,65,-10) + "");
    //Output : Math.max(17,65,-10) = 65
    
    //Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive)
    document.writeln("Math.random() = " + random() + "");
}

Output from The Program

Math.PI = 3.141592653589793

Math.round(96.521) = 97

Math.pow(2,10) = 1024

Math.sqrt(16) = 4

Math.abs(-17.1) = 17.1

Math.ceil(17.1) = 18

Math.floor(17.1) = 17

Math.min(17,65,-10) = -10

Math.max(17,65,-10) = 65

Math.random() = 0.48585420123306733

with 陳述式 (JavaScript)

張貼留言

0 留言