Help Javascript - Microsoft® Microsoft® JScript® JScript...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Microsoft® Microsoft® JScript® JScript Language Reference JScript Tutorial Version Information Feature Information Alphabetic Keyword List Functions Methods Objects Operators Properties Statements Welcome to the JScript Language Reference These handy blocks of information will help you explore the many different parts of JScript. You'll find all the parts of the JScript language listed alphabetically under the Alphabetic Keyword List. But if you want to examine just one category, say, objects, each language category has its own, more compact section. How's it work? Click on one of the headings to the left to display a list of items contained in that category. From this list, select the topic that you want to view. Once you've opened that topic, you can easily link to other related sections. So, go ahead and take a look! Study some statements, mull over the methods, or figure out a few functions. You'll see just how versatile the JScript language can be! ©1998 Microsoft Corporation. All rights reserved. Microsoft® JScript® Feature Information JScript Features - ECMA JScript Features - Non-ECMA Microsoft Scripting Run-Time Features JScript Language Reference Version Information Microsoft® JScript® Alphabetic Keyword List $1...$9 Properties abs Method acos Method ActiveXObject Object Addition Operator (+) anchor Method arguments Property Array Object asin Method Assignment Operator (=) atan Method atan2 Method atEnd Method big Method Bitwise AND Operator (&) Bitwise Left Shift Operator (<<) Bitwise NOT Operator (~) Bitwise OR Operator (|) Bitwise Right Shift Operator (>>) Bitwise XOR Operator (^) blink Method bold Method Boolean Object break Statement caller Property catch Statement @cc_on Statement ceil Method charAt Method charCodeAt Method Comma Operator (,) // (Single-line Comment Statement) /*..*/ (Multiline Comment Statement) Comparison Operators compile Method Compound Assignment Operators concat Method (Array) concat Method (String) Conditional Compilation Conditional Compilation Variables Conditional (trinary) Operator (?:) constructor Property continue Statement cos Method Data Type Conversion JScript Language Reference Version Information Date Object Decrement Operator (--) delete Operator description Property Dictionary Object dimensions Method Division Operator (/) do...while Statement E Property Enumerator Object Equality Operator (==) Error Object escape Method eval Method exec Method exp Method FileSystemObject Object fixed Method floor Method fontcolor Method fontsize Method for Statement for...in Statement fromCharCode Method Function Object function Statement getDate Method getDay Method getFullYear Method getHours Method getItem Method getMilliseconds Method getMinutes Method getMonth Method GetObject Function getSeconds Method getTime Method getTimezoneOffset Method getUTCDate Method getUTCDay Method getUTCFullYear Method getUTCHours Method getUTCMilliseconds Method getUTCMinutes Method getUTCMonth Method getUTCSeconds Method getVarDate Method getYear Method Global Object Greater than Operator (>) Greater than or equal to Operator (>=) Identity Operator (===) @if Statement if...else Statement Increment Operator (++) index Property indexOf Method Inequality Operator (!=) Infinity Property input Property instanceof Operator isFinite Method isNaN Method italics Method item Method join Method Labeled Statement lastIndex Property lastIndexOf Method lbound Method length Property (Array) length Property (Function) length Property (String) Less than Operator (<) Less than or equal to Operator (<=) link Method LN2 Property LN10 Property log Method LOG2E Property LOG10E Property Logical AND Operator (&&) Logical NOT Operator (!) Logical OR Operator (||) match Method Math Object max Method MAX_VALUE Property min Method MIN_VALUE Property Modulus Operator (%) moveFirst Method moveNext Method Multiplication Operator (*) NaN Property (Global) NaN Property (Number) NEGATIVE_INFINITY Property new Operator Nonidentity Operator (!==) Number Object number Property Object Object Operator Precedence parse Method parseFloat Method parseInt Method PI Property POSITIVE_INFINITY Property pow Method prototype Property random Method RegExp Object Regular Expression Object Regular Expression Syntax replace Method return Statement reverse Method round Method ScriptEngine Function ScriptEngineBuildVersion Function ScriptEngineMajorVersion Function ScriptEngineMinorVersion Function search Method @set Statement setDate Method setFullYear Method setHours Method setMilliseconds Method setMinutes Method setMonth Method setSeconds Method setTime Method setUTCDate Method setUTCFullYear Method setUTCHours Method setUTCMilliseconds Method setUTCMinutes Method setUTCMonth Method setUTCSeconds Method setYear Method sin Method slice Method (Array) slice Method (String) small Method sort Method source Property split Method sqrt Method SQRT1_2 Property SQRT2 Property strike Method String Object sub Method substr Method substring Method Subtraction Operator (-) sup Method switch Statement tan Method test Method this Statement throw Statement toArray Method toGMTString Method toLocaleString Method toLowerCase Method toString Method toUpperCase Method toUTCString Method try Statement typeof Operator ubound Method Unary Negation Operator (-) unescape Method Unsigned Right Shift Operator >>>) UTC Method valueOf Method var Statement VBArray Object void Operator while Statement with Statement Microsoft® JScript® Functions GetObject Function ScriptEngine Function ScriptEngineBuildVersion Function ScriptEngineMajorVersion Function ScriptEngineMinorVersion Function JScript Language Reference Version Information Microsoft® JScript® Methods abs Method acos Method anchor Method asin Method atan Method atan2 Method AtEnd Method big Method blink Method bold Method ceil Method charAt Method charCodeAt Method compile Method concat Method (Array) concat Method (String) cos Method dimensions Method escape Method eval Method exec Method exp Method fixed Method floor Method fontcolor Method fontsize Method fromCharCode Method getDate Method getDay Method getFullYear Method getHours Method getItem Method getMilliseconds Method getMinutes Method getMonth Method getSeconds Method getTime Method getTimezoneOffset Method getUTCDate Method getUTCDay Method getUTCFullYear Method getUTCHours Method getUTCMilliseconds Method getUTCMinutes Method getUTCMonth Method JScript Language Reference Version Information getUTCSeconds Method getVarDate Method getYear Method indexOf Method isFinite Method isNaN Method italics Method item Method join Method lastIndexOf Method lbound Method link Method log Method match Method max Method min Method moveFirst Method moveNext Method parse Method parseFloat Method parseInt Method pow Method random Method replace Method reverse Method round Method search Method setDate Method setFullYear Method setHours Method setMilliseconds Method setMinutes Method setMonth Method setSeconds Method setTime Method setUTCDate Method setUTCFullYear Method setUTCHours Method setUTCMilliseconds Method setUTCMinutes Method setUTCMonth Method setUTCSeconds Method setYear Method sin Method slice Method (Array) slice Method (String) small Method sort Method split Method sqrt Method strike Method sub Method substr Method substring Method sup Method tan Method test Method toArray Method toGMTString Method toLocaleString Method toLowerCase Method toString Method toUpperCase Method toUTCString Method ubound Method unescape Method UTC Method valueOf Method Microsoft® JScript® Objects ActiveXObject Object Array Object Boolean Object Date Object Dictionary Object Enumerator Object Error Object FileSystemObject Object Function Object Global Object Math Object Number Object Object Object RegExp Object Regular Expression Object String Object VBArray Object JScript Language Reference Version Information Microsoft® JScript® Operators Addition Operator (+) Assignment Operator (=) Bitwise AND Operator (&) Bitwise Left Shift Operator (<<) Bitwise NOT Operator (~) Bitwise OR Operator (|) Bitwise Right Shift Operator (>>) Bitwise XOR Operator (^) Comma Operator (,) Comparison Operators Compound Assignment Operators Conditional (trinary) Operator (?:) Decrement Operator (--) delete Operator Division Operator (/) Equality Operator (==) Greater than Operator (>) Greater than or equal to Operator (>=) Identity Operator (===) Increment Operator (++) Inequality Operator (!=) instanceof Operator Less than Operator(<) Less than or equal to Operator (<=) Logical AND Operator (&&) Logical NOT Operator (!) Logical OR Operator (||) Modulus Operator (%) Multiplication Operator (*) new Operator Nonidentity Operator (!==) Operator Precedence Subtraction Operator (-) typeof Operator Unary Negation Operator (-) Unsigned Right Shift Operator (>>>) void Operator JScript Language Reference Version Information Microsoft® JScript® Properties $1...$9 Properties arguments Property caller Property constructor Property description Property E Property index Property Infinity Property input Property lastIndex Property (RegExp) length Property (Array) length Property (Function) length Property (String) LN2 Property LN10 Property LOG2E Property LOG10E Property MAX_VALUE Property MIN_VALUE Property Nan Property (Global) NaN Property (Number) NEGATIVE_INFINITY Property number Property PI Property POSITIVE_INFINITY Property prototype Property source Property SQRT1_2 Property SQRT2 Property JScript Language Reference Version Information Microsoft® JScript® Statements break Statement catch Statement @cc_on Statement Comment Statements continue Statement do...while Statement for Statement for...in Statement function Statement @if Statement if...else Statement Labeled Statement return Statement @set Statement switch Statement this Statement throw Statement try Statement var Statement while Statement with Statement JScript Language Reference Version Information Microsoft® JScript® JScript Tutorial What Is JScript? JScript Basics Writing JScript Code JScript Variables JScript Data Types JScript Operators Controlling Program Flow JScript Functions JScript Objects JScript Reserved Keywords Advanced JScript Recursion Variable Scope Copying, Passing, and Comparing Data Using Arrays Advanced Object Creation Special Characters Troubleshooting Your Scripts Using JScript In Internet Explorer Displaying Information in the Browser Using Message Boxes JScript Language Reference Microsoft® JScript® What Is JScript? JScript&nbspTutorial Next JScript is the Microsoft implementation of the ECMA 262 language specification. It is a full implementation, plus some enhancements that take advantage of capabilities of Microsoft Internet Explorer. This tutorial is intended to help you get started with JScript. Easy to Use, Easy to Learn JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than full-fledged object-oriented languages like C++ and Java, JScript is more than sufficiently powerful for its intended purposes. JScript is not a cut-down version of any other language (it is only distantly and indirectly related to Java, for example), and it is not a simplification of anything. It is, however, limited. You cannot write standalone applications in it, for example, and it has little capability for reading or writing files. Moreover, JScript scripts can run only in the presence of an interpreter, either in a Web server or a Web browser. JScript is a loosely typed language. That means you do not have to declare the data types of variables explicitly. Moreover, in many cases JScript performs conversions automatically when they are needed. For instance, if you try to add a number to an item that consists of text (a string), the number is converted to text. The rest of this tutorial is an overview of JScript features. For full details of the language implementation, consult the language reference. Note The code in many of this tutorial's examples is somewhat more explicit and less dense than code you'll find in actual Web pages. Most of it is also fairly simple. The intent here is to clarify the concepts, not to express optimal coding conciseness and style. There is, in any case, no shame in writing code that you can read and easily understand, six months after you write it. Microsoft® JScript® Writing JScript Code JScript&nbspTutorial Previous Next Like many other programming languages, Microsoft JScript is written in text format, and is organized into statements, blocks consisting of related sets of statements, and comments. Within a statement you can use variables , immediate data such as strings and numbers, and expressions. Statements A JScript code statement consists of one or more items and symbols on a line. A new line begins a new statement, but it is a good idea to terminate your statements explicitly. You can do this with the semicolon (;), which is the JScript termination character. aBird = "Robin"; var today = new Date(); A group of JScript statements that is surrounded by braces ({}) is called a block. Blocks of statements are used, for example, in functions and conditionals. In the following example, the first statement begins the definition of a function, which consists of a block of five statements. The last three statements, which are not surrounded by braces, are not a block and are not part of the function definition. function convert(inches) { feet = inches / 12; // These five statements are in a block. miles = feet / 5280; nauticalMiles = feet / 6080; cm = inches * 2.54; meters = inches / 39.37; } km = meters / 1000; // These three statements are not in a block. kradius = km; mradius = miles; Comments A single-line JScript comment begins with a pair of forward slashes (//). A multiline comment begins with a f aGoodIdea = "Comment your code thoroughly."; // This is a single-line comment. /* This is a multiline comment that explains the preceding code statement. The statement assigns a value to the aGoodIdea variable. The value, which is contained */ // // // // This is another multiline comment, written as a series of single-line comments. After the statement is executed, you can refer to the content of the aGoodIdea variable by using its name, as in the next statement, in which a string literal is appended to the aGoodIdea variable by concatenation to create a new variable. var extendedIdea = aGoodIdea + " You never know when you'll have to figure out what it Assignments and Equality The equal sign (=) is used in JScript to indicate the action of assigning a value. That is, a JScript code statement could say anInteger = 3; It means "Assign the value 3 to the variable anInteger," or "anInteger takes the value 3." When you want to compare two values to find out whether they are equal, use a pair of equal signs (==). This is discussed in detail in Controlling Program Flow . Expressions A JScript expression is something that a person can read as a Boolean or numeric expression . Expressions contain symbol characters like "+" rather than words like "added to". Any valid combination of values, variables, operators, and expressions constitutes an expression. var var var var anExpression = "3 * (4 / 5)"; aSecondExpression = "Math.PI * radius * 2"; aThirdExpression = aSecondExpression + "%" + anExpression; aFourthExpression = "(" + aSecondExpression + ") % (" + anExpression + ")"; Microsoft® JScript® JScript Variables JScript&nbspTutorial Previous Next Variables are used in Microsoft JScript to store values in your scripts. They are a way to retrieve and manipulate values using names. When used effectively then can help in understanding what a script does. Declaring Variables Although not required, it is considered good practice to declare variables before using them. You do this usin var statement. The only time you must use the var statement is when declaring variables that are local to a function. Local variables are those that are only within the function. At all other times, using the var stateme declare variables before their use is a recommended practice. The following code examples are of variable declaration: var mim = "A man, a plan, a canal, Panama!"; // The value stored in mim is of string // The sentence in quotes, the value of which is assigned to mim, is a string literal. var ror = 3; // The value stored in ror has numeric type. var nen = true; // The value stored in nen has Boolean type. var fif = 2.718281828 // The value stored in fif has numeric type. Naming Variables JScript is a case-sensitive language, so naming a variable myCounter is different from naming it MYCounter addition, variable names, which can be of any length, must follow certain rules: The first character must be a letter (either uppercase or lowercase) or an underscore (_), or a dollar sig ($). Subsequent characters can be letters, numbers, underscores, or dollar signs. The variable name can't be a reserved word . Some examples of valid variable names: _pagecount Part9 Number_Items Some invalid variable names: 99Balloons // Starts with a number. Smith&Wesson // Ampersand (&) is not a valid character for variable names. In instances in which you want to declare a variable and initialize it, but without giving it any particular valu you may assign it a special value, null . var zaz = null; var notalot = 3 * zaz; // At this point, notalot becomes 0. If you declare a variable without assigning any value to it, it exists but is undefined . var godot; var waitingFor = 1 * godot; // Places the value NaN in waitingFor as godot is undefin You can declare a variable implicitly (without using var ) by assigning a value to it. You cannot, however, us variable that has never been declared at all. To do so generates an error at runtime. lel = ""; // The variable lel is declared implicitly. var aMess = vyv + zez; // Generates an error because vyv and zez don't exist. Coercion As JScript is a loosely-typed language, variables in JScript technically have no fixed type. Instead, they have a type equivalent to the type of the value they contain. It is possible, under some circumstances, to force the automatic conversion (or coercion) of a variable or a piece of data into a different type. Numbers can easily be included in strings, but strings cannot be included directly in numbers, so explicit conversion functions, parseInt() and parseFloat() , are provided. var theFrom = 1; var theTo = 10; var doWhat = "Count from "; doWhat += theFrom + " to " + theTo + "."; After this code is executed, the doWhat variable contains "Count from 1 to 10." The number data have been coerced into string form. var nowWhat = 0; nowWhat += 1 + "10"; // In this case, because "10" is a string, // the "+=" operator concatenates. After this code is executed, the nowWhat variable contains "0110". The following steps are followed to arrive at this result: 1. Look at the types of 1 and "10". The "10" is a string, the 1 is a number, so the number is coerced into a string. 2. As the values on either side of the + operator are both strings, do a string concatenation. This results in "110" 3. Look at the types of the values on either side of the +=. nowWhat contains a number, and 4. 2. 3. "110" is a string, so convert the number to a string. 4. As there are now strings on either side of the += operator, do a string concatentation. This results in "0110". 5. Store this result in nowWhat . var nowThen = 0; nowThen += 1 + parseInt("10"); // In this case, "+=" performs addition. After this code is executed, the nowThen variable contains the integer 11. Microsoft® JScript® JScript Data Types JScript&nbspTutorial Previous Next What Are the JScript Data Types? Microsoft JScript has six types of data. The main types are numbers, strings, objects, and Booleans. The other two are null and undefined . . String Data Type Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.) A string is also an object in JScript, but it is a special case, with special properties. The following are examples of strings: "The cow jumped over the moon." '"Avast, ye lubbers!" roared the technician.' "42" A string can contain zero or more unicode characters. When it contains zero, it is called a zerolength string (""). Number Data Type JScript supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain nu special: NaN , or not a Number Positive Infinity Negative Infinity Positive 0 Negative 0 Integers can be represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Octal integers are specified by a leading "0", and can contain digits 0 through 7. If a number has a leading "0" but contains the dig decimal number. A number that would otherwise be an octal number but contains the letter "e" (or "E") generates an error. Hexadecimal ("hex") integers are specified by a leading "0x" (the "X" can be uppercase or lowercase) and can contain digits 0 thro (either uppercase or lowercase). The letter "e" is a permissible digit in hexadecimal notation and does not signify an exponential nu are used to represent, as single digits, the numbers that are 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is Octal and hexadecimal numbers can be negative, but cannot be fractional. A number that begins with a single "0" and contains a de floating-point number; if a number that begins with "0x" or "00" contains a decimal point, anything to the right of the decimal poin Some example numbers: .0001, 0.0001, 1e-4, 1.0e-4 3.45e2 42 0377 00.0001 0378 0Xff 0x37CF 0x3e7 0x3.45e2 // Four floating-point numbers, equivalent to each other. // A floating-point number, equivalent to 345. // An integer number. // An octal integer, equivalent to 255. // As octal numbers cannot have decimal parts, this is eq // An integer, equivalent to 378. // A hexadecimal integer, equivalent to 255. // A hexadecimal integer, equivalent to 14287. // A hexadecimal integer, equivalent to 999. // As hexadecimal numbers cannot have decimal parts, this Booleans The possible Boolean values are true and false . These are special values, and are not usable as 1 and 0. Note In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true. Thus the following expression evaluates to true: (false == 0) For more information on comparisons, see Controlling Program Flow . Undefined Data Type A value that is undefined is simply a value given to a variable after it has been created, but before a value has been assigned to it. Null Data Type A null value is one that has no value and means nothing. Microsoft® JScript® JScript Operators JScript&nbspTutorial Previous Next JScript has a full range of operators, including arithmetic, logical, bitwise, and assignment operators. There are also a few miscellaneous operators. Computational Logical Bitwise Assignment Miscellaneous Description Symbol Description Symbol Description Symbol Description Symbol Description Symbol Unary negation Logical NOT ! Bitwise NOT ~ Assignment = delete delete Increment ++ Less than < Bitwise Left Shift << Compound Assignment OP = typeof typeof Decrement -Greater than > Bitwise Right Shift >> &nbsp &nbsp void void Multiplication * Less than or equal to <= Unsigned Right Shift >>> &nbsp &nbsp &nbsp &nbsp Division / Greater than or equal to >= Bitwise AND & &nbsp &nbsp &nbsp &nbsp Modulus arithmetic % Equality == Bitwise XOR ^ &nbsp &nbsp &nbsp &nbsp Addition + Inequality != Bitwise OR | &nbsp &nbsp &nbsp &nbsp Subtraction Logical AND && &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Logical OR || &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Conditional (trinary) ?: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Comma , &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Identity === &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Nonidentity !== &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp Operator Precedence Operators in JScript are evaluated in a particular order. This order is known as the operator precedence. The following table lists the operators in highest to lowest precedence order. Operators in the same row are evaluated in left to right order. Operator Description . () Field access, array indexing, and function calls ++ -- - ~ ! typeof new void delete Unary operators, return data type, object creation, undefined values */% Multiplication, division, modulo division +-+ Addition, subtraction, string concatenation << >> >>> Bit shifting < <= > >= Less than, less than or equal to, greater than, greater than or equal to == != === !== Equality, inequality, identity, nonidentity & Bitwise AND ^ Bitwise XOR | Bitwise OR && Logical AND || Logical OR ?: Conditional = OP = Assignment, assignment with operation , Multiple evaluation Parentheses are used to alter the order of evaluation. The expression within parentheses is fully evaluated before its value is used in the remainder of the statement. An operator with higher precedence is evaluated before one with lower precedence. For example: z = 78 * (96 + 3 + 45) There are five operators in this expression: =, *, (), +, and +. According to precedence, they are 1. evaluated in the following order: (), *, +, +, =. 1. Evaluation of the expression within the parentheses is first: There are two addition operators, and they have the same precedence: 96 and 3 are added together and 45 is added to that total, resulting in a value of 144. 2. Multiplication is next: 78 and 144 are multiplied, resulting in a value of 11232. 3. Assignment is last: 11232 is assigned into z. Microsoft® JScript® Controlling Program Flow JScript&nbspTutorial Previous Next Why Control the Flow of Execution? Fairly often, you need a script to do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action. There are several kinds of conditions that you can test. All conditional tests in Microsoft JScript are Boolean, so the result of any test is either true or false . You can freely test values that are of Boolean, numeric, or string type. JScript provides control structures for a range of possibilities. The simplest control structures are the conditional statements. Using Conditional Statements JScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, some JScript code you've written is executed. (In the if...else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if...else statements are much more common. The following examples demonstrate syntaxes you can use with if and if...else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true , the statement or block of statements after the if is executed. // The smash() function is defined elsewhere in the code. if (newShip) smash(champagneBottle,bow); // Boolean test of whether newShip is true. // In this example, the test fails unless both conditions are true. if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles") { theResponse = ("Is it a Crenshaw melon? <br> "); } // In this example, the test succeeds if either condition is true. var theReaction = ""; if ((lbsWeight > 15) || (lbsWeight > 45)) { theReaction = ("Oh, what a cute kitty! <br>"); } else theReaction = ("That's one huge cat you've got there! <br>"); Conditional Operator JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon. var hours = ""; // Code specifying that hours contains either the contents of // theHour, or theHour - 12. hours += (theHour >= 12) ? " PM" : " AM"; Tip If you have several conditions to be tested together, and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&), you can speed execution of your script by putting that condition first in the conditional statement. For example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested. Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code. An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false . if ((runfirst() == 0) || (runsecond() == 0)) // some code Using Repetition, or Loops There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping . It is typically controlled by a test of some variable, the value of which is changed each time the loop is executed. Microsoft JScript supports many types of loops: for loops, for...in loops, while loops, do...while loops, and switch loops. Using for Loops The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After th executed, the counter variable is updated before the next iteration begins. If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop result may be desirable in certain cases, the latter rarely is, so take care when writing your loop conditions. /* The update expression ("icount++" in the following examples) is executed at the end of the loop, after the block of statements that forms the body of the loop is executed, and before the condition is tested. */ var howFar = 11; // Sets a limit of 11 on the loop. var sum = new Array(howFar); var theSum = 0; sum[0] = 0; // Creates an array called sum with 11 members, 0 throug for(var icount = 1; icount < howFar; icount++) theSum += icount; sum[icount] = theSum; } var newSum = 0; for(var icount = 1; icount > howFar; icount++) newSum += icount; } var sum = 0; for(var icount = 1; icount > 0; icount++) sum += icount; } { { // Counts from 1 through 10 i { // This isn't executed at all // This is an infinite loop. Using for...in Loops JScript provides a special kind of loop for stepping through all the properties of an object . The loop counter in a for...in loop steps through all indexes in the array. It is a string, not a number. for (j in tagliatelleVerde) // tagliatelleVerde is an object with several properties { // Various JScript code statements. } Using while Loops The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop. var theMoments = ""; var theCount = 42; // Initialize the counter variable. while (theCount >= 1) { if (theCount > 1) { theMoments = "Only " + theCount + " moments left!"; } else { theMoments = "Only one moment left!"; } theCount--; // Update the counter variable. } theMoments = "BLASTOFF!"; Note Because while loops do not have explicit built-in counter variables, they are even more vulnerable to infinite looping than the other types. Moreover, partly because it is not necessarily easy to discover where or when the loop condition is updated, it is only too easy to write a while loop in which the condition, in fact, never does get updated. You should be extremely careful when you design while loops. Using break and continue Statements Microsoft JScript provides a statement to stop the execution of a loop. The break statement can be used to s (presumably special) condition is met. The continue statement can be used to jump immediately to the nex rest of the code block but updating the counter variable as usual if the loop is a for or for...in loop. var var var var for { theComment = ""; theRemainder = 0; theEscape = 3; checkMe = 27; (kcount = 1; kcount <= 10; kcount++) theRemainder = checkMe % kcount; if (theRemainder == theEscape) { break; // Exits from the loop at the first encounter with a remainder tha } theComment = checkMe + " divided by " + kcount + " leaves a remainder of } " + theRemai for (kcount = 1; kcount <= 10; kcount++) { theRemainder = checkMe % kcount; if (theRemainder != theEscape) { continue; } // Selects only those remainders that equal the escape, ignoring all // JScript code that uses the selected remainders. } var theMoments = ""; var theCount = 42; // The counter is initialized. while (theCount >= 1) { // if (theCount < 10) { // Warning! // This use of continue creates an infinite loop! // continue; // } if (theCount > 1) { theMoments = "Only " + theCount + " moments left!"; } else { theMoments = "Only one moment left!"; } theCount--; // The counter is updated. } theCount = "BLASTOFF!"; Microsoft® JScript® JScript Functions JScript&nbspTutorial Previous Next What Is a Function? Microsoft JScript functions perform actions. They can also return results. Sometimes these are the results of calculations or comparisons. Functions combine several operations under one name. This lets you streamline your code. You can write out a set of statements, name it, and then execute the entire set any time you want to, just by calling it and passing to it any information it needs. You pass information to a function by enclosing the information in parentheses after the name of the function. Pieces of information that are being passed to a function are called arguments or parameters. Some functions don't take any arguments at all; some functions take one argument; some take several. There are even functions for which the number of arguments depends on how you are using the function. JScript supports two kinds of functions: those that are built into the language, and those you create yourself. Special Built-in Functions The JScript language includes several built-in functions. Some of them let you handle expressions and specia characters, and convert strings to numeric values. For example, escape() and unescape() are used to convert characters that have special meanings in HTML code, characters that cannot just put directly into text. For example, the angle brackets, "<" and ">", delineate HTML tags. The escape function takes as its argument any of these special characters, and returns the escape code for the character. Each es code consists of a percent sign (%) followed by a two-digit number. The unescape function is the exact inverse. It takes as its argument a string consisting of a percent sign and a two-digit number, and returns a character. Another useful built-in function is eval() , which evaluates any valid mathematical expression that is presented in string form. The eval() function takes one argument, the expression to be evaluated. var anExpression = "6 * 9 % 7"; var total = eval(anExpression); // Assigns the value 5 to the variable total. var yetAnotherExpression = "6 * (9 % 7)"; total = eval(yetAnotherExpression) // Assigns the value 12 to the variable tota var totality = eval("...surrounded by acres of clams."); // Generates an error. Consult the language reference for more information about these and other built-in functions. Creating Your Own Functions You can create your own functions and use them where you need them. A function definition consists of a fun block of JScript statements. The checkTriplet function in the following example takes as its arguments the lengths of the sides of a triangle, and calculates from is a right triangle by checking whether the three numbers constitute a Pythagorean triplet. (The square of the length of the hypoten equal to the sum of the squares of the lengths of the other two sides.) The checkTriplet function calls one of two other functions to Notice the use of a very small number ("epsilon") as a testing variable in the floating-point version of the test. Because of uncertain floating-point calculations, it is not practical to make a direct test of whether the square of the hypotenuse is equal to the sum of th sides unless all three values in question are known to be integers. Because a direct test is more accurate, the code in this example appropriate and, if it is, uses it. var epsilon = 0.0000000000001; var triplet = false; // Some very small number to test against. function integerCheck(a, b, c) { // The test function for integers. if ( (a*a) == ((b*b) + (c*c)) ) { // The test itself. triplet = true; } } // End of the integer checking function. function floatCheck(a, b, c) { // The test function for floating-point numbers. var theCheck = ((a*a) - ((b*b) + (c*c))) // Make the test number. if (theCheck < 0) { // The test requires the absolute value, so invert theCheck theCheck *= -1; } if (epsilon > theCheck) { // If it's as close as that, it's pretty darn close! triplet = true; } } // End of the floating-poing check function. function checkTriplet(a, b, c) { // The triplet checker. First, move the longest sid var d = 0; // Create a temporary holding bin. if (c > b) { // If c > b, swap them. d = c; c = b; b = d; } // If not, ignore them. if (b > a) { // If b > a, swap them. d = b; b = a; a = d; } // If not, ignore them. // Side "a" is now the hypotenuse, if there is one. } if (((a%1) == 0) && ((b%1) == 0) && ((c%1) == 0)) { // Test all 3 values. Are th integerCheck(a, b, c); // If so, use the precise check. } else floatCheck(a, b, c); // If not, get as close as is reasonably possible. // End of the triplet check function. // The next three statements assign sample values for testing purposes. var sideA = 5; var sideB = 5; var sideC = Math.sqrt(50); checkTriplet(sideA, sideB, sideC); // Call the function. After the call, triplet cont Microsoft® JScript® JScript Objects JScript&nbspTutorial Previous Next What Are Objects? In Microsoft JScript, objects are, essentially, collections of properties and methods. A method is a function that is a member of an object, and a property is a value or set of values (in the form of an array or object) that is a member of an object. JScript supports three kinds of objects: intrinsic objects , objects you create , and browser objects, which are covered elsewhere. Objects as Arrays In JScript, objects and arrays are handled identically. You can refer to any of the members of an object (its p either by name (using the name of the object, followed by a period, followed by the name of the property) o Subscript numbering in JScript begins with 0. For convenience, the subscript can also be referred to by its na Thus, a property can be referred to in several ways. All of the following statements are equivalent. theWidth = spaghetti.width; theWidth = spaghetti[3]; // [3] is the "width" index. theWidth = spaghetti["width"]; While it is possible to use brackets to refer to a property by its numeric index, it is not possible to use the do numbers. The following statement generates an error. theWidth = spaghetti.3; When an object has another object as a property, the naming convention extends in a straightforward way. var init4 = toDoToday.shoppingList[3].substring(0,1); // shoppingList, an array, is a The fact that objects can have other objects as properties lets you generate arrays with more than one subsc supported. The following code creates a multiplication table for values from 0 times 0 through 16 times 16. var multTable = new Array(17); // Make the shell that will become the table. for (var j = 0; j < multTable.length; j++) { // Prepare to fill it with rows. var aRow = new Array(17); // Create a row. for (var i = 0; i < aRow.length; i++) { // Prepare to fill the row. aRow[i] = (i + " times " + j + " = " + i*j); // Make and place one value. } multTable[j] = aRow; // Put the filled row into the table. } To refer to one of the elements of an array of this kind, use multiple sets of brackets. var multiply3x7 = multTable[3][7]; The following statement generates an error. var multiply3x7 = multTable[3, 7]; Microsoft® JScript® JScript&nbspTutorial Previous Next JScript Reserved Keywords JScript has a number of reserved keywords. These words come in three types: JScript reserved keywords, future reserved words, and words to avoid. JScript Keywords break false in this void continue for new true while delete function null typeof with else if return var JScript Future Keywords case debugger export super catch default extends switch class do finally throw const enum import try The words to avoid are any that are already the names of intrinsic JScript objects or functions. Words like String or parseInt are included in this. Using any of the keywords from the first two categories causes a compilation error when your script is first loaded. Using a reserved word from the third set can cause odd behavior problems if you attempt to use both your variable and the original entity of the same name in the same script. For example, the following script does not do quite what you think it should: var String; var text = new String("This is a string object"); In this case, you get an error saying that String is not an object. Many cases of using a preexisting identifier aren't this obvious. Microsoft® JScript® Recursion JScript&nbspTutorial Previous Next Recursion is an important programming technique. It's used to have a function call itself from within itself. O example is the calculation of factorials. The factorials of 0 and 1 are both defined specifically to be 1. The fac larger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number for w calculating the factorial. The following paragraph is a function, defined in words, that calculates a factorial. "If the number is less than zero, reject it. If it isn't an integer, round it down to the next integer. If the number is zero or one, its fa If the number is larger than one, multiply it by the factorial of the next smaller number." To calculate the factorial of any number that is larger than 1, you need to calculate the factorial of at least one other number. The f use to do that is the function you're in the middle of already; the function must call itself for the next smaller number, before it can the current number. This is an example of recursion. Clearly, there is a way to get in trouble here. You can easily create a recursive function that doesn't ever get to a definite result, an reach an endpoint. Such a recursion causes the computer to execute a so-called "infinite" loop. Here's an example: omit the first ru about negative numbers) from the verbal description of calculating a factorial, and try to calculate the factorial of any negative num because in order to calculate the factorial of, say, -24 you first have to calculate the factorial of -25; but in order to do that you firs calculate the factorial of -26; and so on. Obviously, this never reaches a stopping place. Thus, it is extremely important to design recursive functions with great care. If you even suspect that there's any chance of an infin you can have the function count the number of times it calls itself. If the function calls itself too many times, however many you de should be, it automatically quits. Here's the factorial function again, this time written in JScript code. function factorial(aNumber) { aNumber = Math.floor(aNumber); // If the number is not an integer, round it down. if (aNumber < 0) { // If the number is less than zero, reject it. return "not a defined quantity"; } if ((anumber == 0) || (anumber == 1)) { // If the number is 0 or 1, its factor return 1; } else return (anumber * factorial(anumber - 1)); // Otherwise, recurse until d } Microsoft® JScript® Variable Scope JScript&nbspTutorial Previous Next Microsoft JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. and destroyed every time the function is executed; it cannot be accessed by anything outside the function. A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the va variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning. var aCentaur = "a horse with rider,"; // Global definition of aCentaur. // JScript code, omitted for brevity. function antiquities() // A local aCentaur variable is declared in this function. { // JScript code, omitted for brevity. var aCentaur = "A centaur is probably a mounted Scythian warrior"; // JScript code, omitted for brevity. aCentaur += ", misreported; that is, "; // Adds to the local variable. // JScript code, omitted for brevity. } // End of the function. var nothinginparticular = antiquities(); aCentaur += " as seen from a distance by a naive innocent."; /* Within the function, the variable contains "A centaur is probably a mounted Scythian w misreported; that is, "; outside the function, the variable contains the rest of the s "a horse with rider, as seen from a distance by a naive innocent." */ It's important to note that variables act as if they were declared at the beginning of whatever scope they exis Sometimes this results in unexpected behaviors. var aNumber = 100; var withAdditive = 0; withAdditive += aNumber; tweak(); withAdditive += aNumber; function tweak() { // withAdditive is now 100. // withAdditive is now 200. var newThing = 0; // Explicit declaration of the newThing variable. // The next statement, if it were not commented out, would generate an error. // newThing = aNumber; // The next statement assigns the value 42 to the local aNumber, implicitly declaring aNumber = 42; if (false) { var aNumber; // This statement is never executed. aNumber = "Hello!"; // This statement is never executed. } // End of the conditional. } // End of the function definition. The statement that is commented out attempts to assign the value of the local variable aNumber to the local newThing . It fails, despite the fact that a local aNumber variable is defined elsewhere in the function, and th exists throughout. The aNumber variable does not have any assigned value at the point where this statemen the code, and is thus undefined . Microsoft® JScript® Copying, Passing, and Comparing Data JScript Tutorial Previous Next In Microsoft JScript, how data is handled depends on its data type. By Value vs. By Reference Numbers and Boolean values (true and false) are copied, passed, and compared by value. When you copy or pass by value, you allocate a space in computer memory and put the value of the original into it. If you then change the original, the copy is not affected (and vice versa), because the two are separate entities. Objects, arrays, and functions are copied, passed, and compared by reference under most circumstances. When you copy or pass by reference, you essentially create a pointer to the original item, and use the pointer as if it were a copy. If you then change the original, you change both the original and the copy (and vice versa). There is really only one entity; the "copy" is not actually a copy, it's just another reference to the data. Note You can change this behavior for objects and arrays by specifying the assign( ) method for them. Last, strings are copied and passed by reference, but are compared by value. Note Because of the way the ASCII and ANSI character sets are constructed, capital letters precede lowercase ones in sequence order. For example, "Zoo" compares as less than "aardvark." Passing Parameters to Functions When you pass a parameter to a function by value, you are making a separate copy of that parameter, a copy that exists only inside the function. If, on the other hand, you pass a parameter by reference, and the function changes the value of that parameter, it is changed everywhere in the script. Testing Data When you perform a test by value, you compare two distinct items to see whether they are equal to each other. Usually, this comparison is performed on a byte-by-byte basis. When you test by reference, you are checking to see whether two items are pointers to a single original item. If they are, then they compare as equal; if not, even if they contain the exact same values, byte-for-byte, they compare as unequal. Copying and passing strings by reference saves memory; but because you cannot change strings once they are created, it becomes possible to compare them by value. This lets you test whether two strings have the same content even if one was generated entirely separately from the other. Microsoft® JScript® Using Arrays JScript Tutorial Previous Next Array Indexing Arrays in JScript are sparse. That is, if you have an array with three elements that are numbered 0, 1, and 2, you can create element 50 without worrying about elements 3 through 49. If the array has an automatic length variable (see Intrinsic Objects for an explanation of automatic monitoring of array length), the length variable is set to 51, rather than to 4. You can certainly create arrays in which there are no gaps in the numbering of elements, but you aren't required to. In fact, in JScript, your arrays don't have to have numbered subscripts at all. In JScript, objects and arrays are essentially identical to each other. The real difference is not in the data, but rather in the way you address the members of an array or the properties and methods of an object. Addressing Arrays There are two main ways to address the members of an array. Ordinarily, you address arrays by using brackets. The brackets enclose either a numeric value or an expression that evaluates to a nonnegative integer. The following example assumes that the entryNum variable is defined and assigned a value elsewhere in the script. theListing = addressBook[entryNum]; theFirstLine = theListing[1]; This method of addressing is equivalent to the method for addressing objects, though in object addressing, what follows the period must be the name of an actual property. If there is no such property, your code generates an error. The second way to address an array is to make an object/array that contains properties that are numbered, and then generate the numbers in a loop. The following example generates two arrays, one for the name and one for the address, from a listing in addressBook. Each of these contains four properties. An instance of theName, for example, built from the [Name1] through [Name4] properties of theListing, might contain "G." "Edward" "Heatherington" "IV", or "George" "" "Sand" "". theListing = addressBook[entryNum]; for (i = 1; i < 4; i++) { theName[i] = theListing["Name" + i]; theAddress[i] = theListing["Address" + i]; } While this particular instance is short, and could easily have been written in the "dot" style of notation, (that is, addressing theListing, theName, and theAddress as objects rather than as arrays), that is not always possible. Sometimes the particular property may not exist until run time, or there may be no way to know which one it will be in advance. For example, if the addressBook array were arranged by last name instead of by numbered listings, the user would probably be entering names "on the fly," while the script is running, to look people up. The following example assumes the existence of appropriate function definitions elsewhere in the script. theListing = addressBook[getName()]; theIndivListing = theListing[getFirstName()]; This is associative addressing of the array, that is, addressing by means of fully arbitrary strings. Objects in JScript are actually associative arrays. Although you can (and frequently do) use the "dot" style of addressing, you are not by any means required to. Because the members of any JScript object can be accessed using array notation, a JScript object can be used as an associative array. The following code creates and initializes the most familiar form of an array: var myArray = new Array("Athens", "Belgrade", "Cairo"); Each element of this array is addressed using its element number; in this case 0, 1, or 2. Using the for...in statement, the array can be iterated starting at 0 and ending at 2. For example: for (key in myArray) response.write("Element value is " + MyArray[key] + "<BR>); The following code creates and initializes an associative array containing three elements: var MyArray = {"a" : "Athens", "b" : "Belgrade", "c" : "Cairo" }; In this array, elements are addressed using the key strings("a", "b", or "c") instead of an array element number (0, 1, or 2). This allows you to create and use arrays with more intuitive addressing schemes. The same for...in statement code shown above can be used to iterate this array as well. Microsoft® JScript® Advanced Object Creation JScript Tutorial Previous Next Using Constructors to Create Objects In Microsoft JScript, you use constructors to create and build a class of objects . You invoke a constructor wit The special case Function constructor lets you create functions that are anonymous . An anonymous function is one that does not h which is only called from the one location, doesn't need a name. In the following example, such an anonymous function generates one line of a "name-and-email-address" listing. It checks the valu the name or the email address first. The example assumes that the values of firstNameFirst and emailNameFirst are set elsewhere. for (j = 1; j < addressList[length]; j++) { oneListingLine = new Function(emailNameFirst, firstNameFirst, addressList, j, theName if(firstNameFirst) { theName=(addressList[j].firstName + addressList[j].lastName); },) ; if (emailNameFirst) { theListing = addressList[j].emailName+ ":\t" + theName } else theListing = theName + ":\t" + addressList[j].emailName; return theListin document.write(oneListingLine + "<br>"); } Writing Constructors To write your own constructors, you use the this keyword within the constructor to refer to the newly-created object. The constructor initializes the object. Though the constructor in the next example starts at an index of 0, this is not required. You can start with a first index of 1 if, for example, you want a parameter that indicates the actual number of indexes of the array or object. In the example, it's called extent to distinguish it from the automatically maintained length parameter of the built-in Array( ) object). If you write code that adds properties to the array, you have to update the extent parameter (or your equivalent) because this parameter is not maintained by JScript. Notice that even this extremely simple example uses both object (dot) and array (bracket) notation styles to refer to the current object. function MakeStringArray(length) { this.extent = length; for (iNum = 0; iNum < length; i++) { this[iNum] = ""; } } // Use the constructor to create and initialize an array. myStringArray = new MakeStringArray(63); Using Prototypes to Create Objects When you write an object definition, you can use prototype properties to create properties that are held in co all objects that are generated by the definition. Prototype properties are copied by reference into each object so they have the same value for all objects in the class. However, you can change the value of a prototype p one object, and the new value overrides the default, but only in that one instance. Other objects that are me the class are not affected by the change. Using this principle, you can define additional properties for objects that are part of the JScript language, which all have prototypes if you want a special constant for a calculation, and the constant is not among those provided in the Math and Number objects, yo yourself and then assign it their respective object prototypes, or the prototype property of your object class. Math.prototype.Avogadro = 6.0232E23; function howManyMolecules(wtGrams,molWt) { return ((wtGrams/molWt)*Math.prototype.Avogadro); } document.write("There are " + howManyMolecules(window.prompt("How many grams?",0),wind ("What's the molecular weight?",0)) + " molecules in that amount."); Perhaps more to the point, you can define a function, assign it to String.prototype as a method, and use it on anywhere in your script. The following example assumes the existence of a Periodic Chart array called "theEl defined elsewhere in the script, which contains symbols for the elements, their names, their atomic weights, relevant information about them. function atomName(theSymbol) { return(theElements[theSymbol].fullName); } String.prototype.atomName = atomName; function decodeFormula(theFormula) { var theCurrentPiece = ""; var theDecodedFormula = ""; for (i = 1; i = theFormula.length ; i++); if (theFormtheCurrentPiece // Code statements to separate the formula string into an array of symbols and numbers // Loop through the formula array and assemble the decoded string. Each term is: theDecodedFormula += formula[n].number theDecodedFormula += " "; theDecodedFormula += formula[n].symbol.prototype.atomName; theDecodedFormula += " " // End of loop. return theDecodedFormula; } decodeFormula(window.prompt("Formula?","Al2O3")); Microsoft® JScript® Special Characters JScript Tutorial Previous Next Special Characters JScript provides special characters that allow you to include in strings some characters you can't type directly of these characters begins with a backslash. The backslash is an escape character you use to inform the JScr interpreter that the next character is special. \b Backspace \f Form feed \n Line feed (newline) \r Carriage return \t Horizontal tab (Ctrl-I) \' Single quotation mark \" Double quotation mark \\ Backslash Escape Sequence Character Notice that because the backslash itself is used as the escape character, you cannot directly type one in your script. If you want to backslash, you must type two of them together (\\). document.write('The image path is C:\\webstuff\\mypage\\gifs\\garden.gif.'); document.write('The caption reads, "After the snow of \'97. Grandma\'s house is covere You can use these escape sequences to control formatting of text inside <PRE> and <XMP> tags and, to som extent, inside alert, prompt, and confirm message boxes. Microsoft® JScript® Troubleshooting Your Scripts JScript Tutorial Previous Next There are places in any programming language where you can get caught if you are not careful, and every language has specific surprises in it. Take, for example, the null value: The one in Microsoft JScript behaves differently than the null value in the C or C++ languages. Here are some of the trouble areas that that you may run into as you write JScript scripts. Syntax Errors Because syntax is much more rigid in programming languages than in natural languages, it is important to pay strict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be a string, you will run into trouble if you forget to enclose it in quotation marks when you type it. Order of Script Interpretation JScript interpretation is part of the your Web browser's HTML parsing process. So, if you place a script inside the <HEAD> tag in a document, it is interpreted before any of the <BODY> tag is examined. If you have objects that are created in the <BODY> tag, they do not exist at the time the <HEAD> is being parsed, and cannot be manipulated by the script. Automatic Type Coercion JScript is a loosely typed language with automatic coercion. Consequently, despite the fact that values having different types are not equal, the expressions in the following example evaluate to true. "100" == 100 false == 0 Operator Precedence When a particular operation is performed during the evaluation of an expression has more to do with operator precedence than with the location of the expression. Thus, in the following example, multiplication is performed before subtraction, even though the subtraction appears first in the expression. theRadius = aPerimeterPoint - theCenterpoint * theCorrectionFactor; Using for...in Loops with Objects When you step through the properties of an object with a for...in loop, you cannot necessarily predict or control the order in which the fields of the object are assigned to the loop counter variable. Moreover, the order may be different in different implementations of the language. with Keyword The with statement is convenient for addressing properties that already exist in a specified object, but cannot be used to add properties to an object. To create new properties in an object, you must refer to the object specifically. this Keyword Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannot ordinarily use this or similar keywords to refer to the currently executing function when that function is not an object definition. You can, if the function is to be assigned to an object as a method, use the this keyword within the function, to refer to the object. Writing a Script That Writes a Script The </SCRIPT> tag terminates the current script if the interpreter encounters it. To display "" itself, rewrite this as at least two strings, for example, "</SCR" and "IPT>", which you can then concatenate together in the statement that writes them out. Implicit Window References Because more than one window can be open at a time, any window reference that is implicit is taken to point to the current window. For other windows, you must use an explicit reference. Microsoft® JScript® Displaying Information In the Browser JScript Tutorial Previous Next Microsoft JScript provides two ways to display data directly in your browser. You can use the write( ) and writeln( ) , which are methods of the document object. You can also display information in forms within the browser, and in alert, prompt, and confirm message boxes. Using document.write( ) and document.writeln( ) The most common way to display information is the write( ) method of the document object. It takes one argument, a string, which it displays in the browser. The string can be either plain text or HTML. Strings can be enclosed in either single or double quotation marks. This lets you quote something that contains quote marks or apostrophes. document.write("Pi is approximately equal to " + Math.PI); document.write( ); Tip The following simple function is a way around having to type "document.write" every time you want something to appear in the browser window. This function does not inform you if something that you attemp write is undefined, but does let you issue the command "w();", which displays a blank line. function w(m) { // Write function. m = "" + m + ""; // Make sure that the m variable is a string. if ("undefined" != m) { // Test for empty write or other undefined item. document.write(m); } document.write("<br>"); } w('<IMG SRC="horse.gif">'); w(); w("This is an engraving of a horse."); w(); The writeln( ) method is almost identical to the write( ) method, except that it appends a newline character to whatever string yo provide. In HTML this ordinarily results only in a space after your item; but if you're using <PRE> and <XMP> tags, the newline ch is interpreted literally and the browser displays it. When you call the write( ) method, it opens and clears the document if the document is not in the process of being opened and pa when the write( ) method is called, so it can be dangerous. The example shows a script that is intended to display the time once a but fails to do so after the first time because it clears itself in the process. <HTML> <HEAD> <SCRIPT LANGUAGE="JScript"> function singOut() { var theMoment = new Date(); var theHour = theMoment.getHours(); var theMinute = theMoment.getMinutes(); var theDisplacement = (theMoment.getTimezoneOffset() / 60); theHour -= theDisplacement; if (theHour > 23) { theHour -= 24 } document.write(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Tim window.setTimeout("singOut();", 60000); } </SCRIPT> </HEAD> <BODY> <SCRIPT> singOut(); </SCRIPT> </BODY> </HTML> If you use the alert() method of the window object instead of document.write() , the script works. window.alert(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Time. window.setTimeout("singOut();", 60000); } Clearing the Current Document The clear() method of the document object empties the current document. This method also clears your script (along with the rest of the document), so be very careful how and when you use it. document.clear(); Microsoft® JScript® Using Message Boxes JScript Tutorial Previous Using alert, prompt, and confirm Use alert, confirm, and prompt message boxes to obtain input from your user. The boxes are methods of the interface window object. Because the window object is at the top of the object hierarchy, you do not actually have to use the full name (for example, "window.alert()") of any of these message boxes, but it is a good idea to do so, because it helps you remember to which object they belong. Alert Message Box The alert method has one argument, the string of text you want to display to the user. The string is not HTML. The message box provides an OK button so the user can close it and is modal, that is, the user must close the message box before continuing. window.alert("Welcome! Press OK to continue."); Confirm Message Box The confirm message box lets you ask the user a "yes-or-no" question, and gives the user the option of clicking either an OK button or a Cancel button. The confirm method returns either true or false . This message box is also modal: the user must respond to it (click a button), and thereby close it, before proceeding. var truthBeTold = window.confirm("Click OK to continue. Click Cancel to stop."); if (truthBeTold) { window.alert("Welcome to our Web page!"); } else window.alert("Bye for now!"); Prompt Message Box The prompt message box provides a text field in which the user can type an answer in response to your prompt. This box has an OK button and a Cancel button. If you provide a second string argument, the prompt message box displays that second string in the text field, as the default response. Otherwise, the default text is "<undefined>". Like the alert( ) and confirm( ) methods, prompt displays a modal message box. The user must close it before continuing. var theResponse = window.prompt("Welcome?","Enter your name here."); Microsoft® JScript® Scripting Run-Time Library Reference Language Reference Version Information Feature Information Alphabetic Keyword List Welcome to the Scripting Run-Time Library Reference Methods Objects Properties These handy blocks of information will help you explore the many different parts of the Scripting RunTime Library. You'll find all the parts of the Scripting Run-Time Library listed alphabetically under the Alphabetic Keyword List. But if you want to examine just one category, say, objects, each language category has its own, more compact section. How's it work? Click on one of the headings to the left to display a list of items contained in that category. From this list, select the topic that you want to view. Once you've opened that topic, you can easily link to other related sections. So, go ahead and take a look! Study some statements, mull over the methods, or figure out a few functions. You'll see just how versatile the Scripting Run-Time Library can be! ©1998 Microsoft Corporation. All rights reserved. Microsoft® JScript® Feature Information Microsoft Scripting Run-Time Features Scripting Run-Time Library Reference Version Information Microsoft® JScript® Alphabetic Keyword List Add Method (Dictionary) Add Method (Folders) AtEndOfLine Property AtEndOfStream Property Attributes Property AvailableSpace Property BuildPath Method Close Method Column Property CompareMode Property Copy Method CopyFile Method CopyFolder Method Count Property CreateFolder Method CreateTextFile Method DateCreated Property DateLastAccessed Property DateLastModified Property Delete Method DeleteFile Method DeleteFolder Method Dictionary Object Drive Object Drive Property DriveExists Method DriveLetter Property Drives Collection Drives Property DriveType Property Exists Method File Object FileExists Method Files Collection Files Property FileSystem Property FileSystemObject Object Folder Object FolderExists Method Folders Collection FreeSpace Property GetAbsolutePathName Method GetBaseName Method GetDrive Method GetDriveName Method Scripting Run-Time Library Reference Version Information GetExtensionName Method GetFile Method GetFileName Method GetFolder Method GetParentFolderName Method GetSpecialFolder Method GetTempName Method IsReady Property IsRootFolder Property Item Property Items Method Key Property Keys Method Line Property Move Method MoveFile Method MoveFolder Method Name Property OpenAsTextStream Method OpenTextFile Method ParentFolder Property Path Property Read Method ReadAll Method ReadLine Method Remove Method RemoveAll Method RootFolder Property SerialNumber Property ShareName Property ShortName Property ShortPath Property Size Property Skip Method SkipLine Method SubFolders Property TextStream Object TotalSize Property Type Property VolumeName Property Write Method WriteBlankLines Method WriteLine Method Microsoft® JScript® Methods Add Method (Dictionary) Add Method (Folders) BuildPath Method Close Method Copy Method CopyFile Method CopyFolder Method CreateFolder Method CreateTextFile Method Delete Method DeleteFile Method DeleteFolder Method DriveExists Method Exists Method FileExists Method FolderExists Method GetAbsolutePathName Method GetBaseName Method GetDrive Method GetDriveName Method GetExtensionName Method GetFile Method GetFileName Method GetFolder Method GetParentFolderName Method GetSpecialFolder Method GetTempName Method Items Method Keys Method Move Method MoveFile Method MoveFolder Method OpenAsTextStream Method OpenTextFile Method Read Method ReadAll Method ReadLine Method Remove Method RemoveAll Method Skip Method SkipLine Method Write Method WriteBlankLines Method WriteLine Method Scripting Run-Time Library Reference Version Information Microsoft® JScript® Objects Dictionary Object Drive Object Drives Collection File Object Files Collection FileSystemObject Object Folder Object Folders Collection TextStream Object Scripting Run-Time Library Reference Version Information Microsoft® JScript® Properties AtEndOfLine Property AtEndOfStream Property Attributes Property AvailableSpace Property Column Property CompareMode Property Count Property DateCreated Property DateLastAccessed Property DateLastModified Property Drive Property DriveLetter Property Drives Property DriveType Property Files Property FileSystem Property FreeSpace Property IsReady Property IsRootFolder Property Item Property Key Property Line Property Name Property ParentFolder Property Path Property RootFolder Property SerialNumber Property ShareName Property ShortName Property ShortPath Property Size Property SubFolders Property TotalSize Property Type Property VolumeName Property Scripting Run-Time Library Reference Version Information Microsoft® JScript™ FileSystemObject Object Tutorial The FileSystemObject Object Model Introduction to the FileSystemObject and the Scripting Run-Time Library Reference FileSystemObject Objects Programming the FileSystemObject Working with Drives and Folders Working with Files FileSystemObject Sample Code Scripting Run-Time Library Reference Microsoft® Scripting Library - FileSystemObject Next The FileSystemObject Object Model When writing scripts for Active Server Pages, the Windows Scripting Host, or other applications where scripting can be used, it's often important to add, move, change, create, or delete folders (directories) and files on the Web server. It may also be necessary to get information about and manipulate drives attached to the Web server. Scripting allows you to process drives, folders, and files using the FileSystemObject (FSO) object model, which is explained in the following sections: Introduction to the FileSystemObject and the Scripting Run-Time Library Reference FileSystemObject Objects Programming the FileSystemObject Working with Drives and Folders Working with Files FileSystemObject Sample Code Microsoft® Scripting Library - FileSystemObject Introduction to the FileSystemObject and the Scripting Run-Time Library Reference Previous Next The FileSystemObject (FSO) object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files. Use this object-based tool with: HTML to create Web pages Windows Scripting Host to create batch files for Microsoft Windows Script Control to provide a scripting capability to applications developed in other languages Because use of the FSO on the client side raises serious security issues about providing potentially unwelcome access to a client's local file system, this documentation assumes use of the FSO object model to create scripts executed by Internet Web pages on the server side. Since the server side is used, the Internet Explorer default security settings do not allow client-side use of the FileSystemObject object. Overriding those defaults could subject a local computer to unwelcome access to the file system, which could result in total destruction of the file system's integrity, causing loss of data, or worse. The FSO object model gives your server-side applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. You can also find out information about folders, such as their names, the date they were created or last modified, and so forth. The FSO object model also makes it easy to process files. When processing files, the primary goal is to store data in a spaceand resource-efficient, easy-to-access format. You need to be able to create files, insert and change the data, and output (read) the data. Since storing data in a database, such as Access or SQL Server, adds a significant amount of overhead to your application, storing your data in a binary or text file may be the most efficient solution. You may prefer not to have this overhead, or your data access requirements may not require all the extra features associated with a full-featured database. The FSO object model, which is contained in the Scripting type library (Scrrun.dll), supports text file creation and manipulation through the TextStream object. Although it does not yet support the creation or manipulation of binary files, future support of binary files is planned. Microsoft® Scripting Library - FileSystemObject FileSystemObject Objects The FileSystemObject (FSO) object model contains the following objects and collections. Object/Collection Description FileSystemObject Main object. Contains methods and properties that allow you to create, delete, gain information about, and generally manipulate drives, folders, and files. Many of the methods associated with this object duplicate those in other FSO objects; they are provided for convenience. Drive Object. Contains methods and properties that allow you to gather information about a drive attached to the system, such as its share name and how much room is available. Note that a "drive" isn't necessarily a hard disk, but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the system; it can be also be logically connected through a network. Drives Collection. Provides a list of the drives attached to the system, either physically or logically. The Drives collection includes all drives, regardless of type. Removable-media drives need not have media inserted for them to appear in this collection. File Object. Contains methods and properties that allow you to create, delete, or move a file. Also allows you to query the system for a file name, path, and various other properties. Files Collection. Provides a list of all files contained within a folder. Folder Object. Contains methods and properties that allow you to create, delete, or move folders. Also allows you to query the system for folder names, paths, and various other properties. Folders Collection. Provides a list of all the folders within a Folder. TextStream Object. Allows you to read and write text files. Previous Next Microsoft® Scripting Library - FileSystemObject Programming the FileSystemObject Previous Next To program with the FileSystemObject (FSO) object model: Use the CreateObject method to create a FileSystemObject object. Use the appropriate method on the newly created object. Access the object's properties. The FSO object model is contained in the Scripting type library, which is located in the Scrrun.dll file. Therefore, you must have Scrrun.dll in the appropriate system directory on your Web server to use the FSO object model. Creating a FileSystemObject Object First, create a FileSystemObject object by using the CreateObject method. In VBScript, use the following code to create an instance of the FileSystemObject: Dim fso Set fso = CreateObject("Scripting.FileSystemObject") This sample code demonstrates how to create an instance of the FileSystemObject. In JScript, use this code to do the same thing: var fso; fso = new ActiveXObject("Scripting.FileSystemObject"); In both of these examples, Scripting is the name of the type library and FileSystemObject is the name of the object that you want to create. You can create only one instance of the FileSystemObject object, regardless of how many times you try to create another. Using the Appropriate Method Second, use the appropriate method of the FileSystemObject object. For example, to create a new object, use either CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or deletion of drives). To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects. You can also copy and move files and folders, by using the appropriate methods. Note Some functionality in the FileSystemObject object model is redundant. For example, you can copy a file using either the CopyFile method of the FileSystemObject object, or you can use the Copy method of the File object. The methods work the same; both exist to offer programming flexibility. Accessing Existing Drives, Files, and Folders To gain access to an existing drive, file, or folder, use the appropriate "get" method of the FileSystemObject object: GetDrive GetFolder GetFile To gain access to an existing file in VBScript: Dim fso, f1 Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.GetFile("c:\test.txt") To do the same thing in JScript, use the following code: var fso, f1; fso = new ActiveXObject("Scripting.FileSystemObject"); f1 = fso.GetFile("c:\\test.txt"); Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object. For example, if you create a new folder using the CreateFolder method, don't use the GetFolder method to access its properties, such as Name, Path, Size, and so forth. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, then access its properties, methods, and events. To do this in VBScript, use the following code: Sub CreateFolder Dim fso, fldr Set fso = CreateObject("Scripting.FileSystemObject") Set fldr = fso.CreateFolder("C:\MyTest") Response.Write "Created folder: " & fldr.Name End Sub To set a variable to the CreateFolder function in JScript, use this syntax: function CreateFolder() { var fso, fldr; fso = ActiveXObject("Scripting.FileSystemObject"); fldr = fso.CreateFolder("C:\\MyTest"); Response.Write("Created folder: " + fldr.Name); } Accessing the Object's Properties Once you have a handle to an object, you can access its properties. For example, to get the name of a particular folder, first create an instance of the object, then get a handle to it with the appropriate method (in this case, the GetFolder method, since the folder already exists). Use this code to get a handle to the GetFolder method in VBScript: Set fldr = fso.GetFolder("c:\") To do the same thing in JScript, use the following code: var fldr = fso.GetFolder("c:\\"); Now that you have a handle to a Folder object, you can check its Name property. Use the following code to check this in VBScript: Response.Write "Folder name is: " & fldr.Name To check a Name property in JScript, use this syntax: Response.Write("Folder name is: " + fldr.Name); To find out the last time a file was modified, use the following VBScript syntax: Dim fso, f1 Set fso = CreateObject("Scripting.FileSystemObject") ' Get a File object to query. Set f1 = fso.GetFile("c:\detlog.txt") ' Print information. Response.Write "File last modified: " & f1.DateLastModified To find out the same thing in JScript, use this code: var fso, f1; fso = new ActiveXObject("Scripting.FileSystemObject"); // Get a File object to query. f1 = fso.GetFile("c:\\detlog.txt"); // Print information. Response.Write("File last modified: " + f1.DateLastModified); Microsoft® Scripting Library - FileSystemObject Working with Drives and Folders Previous Next With the FileSystemObject (FSO) object model, you can work with drives and folders programmatically just as you can in the Windows Explorer interactively. You can copy and move folders, get information about drives and folders, and so forth. Getting Information About Drives The Drive object allows you to gain information about the various drives attached to a system, either physically or over a network. Its properties allow you to obtain information about: The total size of the drive in bytes (TotalSize property) How much space is available on the drive in bytes (AvailableSpace or FreeSpace properties) What letter is assigned to the drive (DriveLetter property) What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk (DriveType property) The drive's serial number (SerialNumber property) The type of file system the drive uses, such as FAT, FAT32, NTFS, and so forth (FileSystem property) Whether a drive is available for use (IsReady property) The name of the share and/or volume (ShareName and VolumeName properties) The path or root folder of the drive (Path and RootFolder properties) View the sample code to see how these properties are used in FileSystemObject. Example Usage of the Drive Object Use the Drive object to gather information about a drive. You won't see a reference to an actual Drive object in the following code; instead, use the GetDrive method to get a reference to an existing Drive object (in this case, drv). The following example demonstrates how to use the Drive object in VBScript: Sub ShowDriveInfo(drvPath) Dim fso, drv, s Set fso = CreateObject("Scripting.FileSystemObject") Set drv = fso.GetDrive(fso.GetDriveName(drvPath)) s = "Drive " & UCase(drvPath) & " - " s = s & drv.VolumeName & "<br>" s = s & "Total Space: " & FormatNumber(drv.TotalSize / 1024, 0) s = s & " Kb" & "<br>" s = s & "Free Space: " & FormatNumber(drv.FreeSpace / 1024, 0) s = s & " Kb" & "<br>" Response.Write s End Sub The following code illustrates the same functionality in JScript: function ShowDriveInfo1(drvPath) { var fso, drv, s =""; fso = new ActiveXObject("Scripting.FileSystemObject"); drv = fso.GetDrive(fso.GetDriveName(drvPath)); s += "Drive " + drvPath.toUpperCase()+ " - "; s += drv.VolumeName + "<br>"; s += "Total Space: " + drv.TotalSize / 1024; s += " Kb" + "<br>"; s += "Free Space: " + drv.FreeSpace / 1024; s += " Kb" + "<br>"; Response.Write(s); } Working with Folders Common folder tasks and the methods for performing them are described in the following table. Task Method Create a folder. FileSystemObject.CreateFolder Delete a folder. Folder.Delete or FileSystemObject.DeleteFolder Move a folder. Folder.Move or FileSystemObject.MoveFolder Copy a folder. Folder.Copy or FileSystemObject.CopyFolder Retrieve the name of a folder. Folder.Name Find out if a folder exists on a drive. FileSystemObject.FolderExists Get an instance of an existing Folder object. FileSystemObject.GetFolder Find out the name of a folder's parent folder. FileSystemObject.GetParentFolderName Find out the path of system folders. FileSystemObject.GetSpecialFolder View the sample code to see how many of these methods and properties are used in FileSystemObject. The following example demonstrates how to use the Folder and FileSystemObject objects to manipulate folders and gain information about them in VBScript: Sub ShowFolderInfo() Dim fso, fldr, s ' Get instance of FileSystemObject. Set fso = CreateObject("Scripting.FileSystemObject") ' Get Drive object. Set fldr = fso.GetFolder("c:") ' Print parent folder name. Response.Write "Parent folder name is: " & fldr & "<br>" ' Print drive name. Response.Write "Contained on drive " & fldr.Drive & "<br>" ' Print root file name. If fldr.IsRootFolder = True Then Response.Write "This is the root folder." & ""<br>"<br>" Else Response.Write "This folder isn't a root folder." & "<br><br>" End If ' Create a new folder with the FileSystemObject object. fso.CreateFolder ("C:\Bogus") Response.Write "Created folder C:\Bogus" & "<br>" ' Print the base name of the folder. Response.Write "Basename = " & fso.GetBaseName("c:\bogus") & "<br>" ' Delete the newly created folder. fso.DeleteFolder ("C:\Bogus") Response.Write "Deleted folder C:\Bogus" & "<br>" End Sub This example shows how to use the Folder and FileSystemObject objects in JScript: function ShowFolderInfo() { var fso, fldr, s = ""; // Get instance of FileSystemObject. fso = new ActiveXObject("Scripting.FileSystemObject"); // Get Drive object. fldr = fso.GetFolder("c:"); // Print parent folder name. Response.Write("Parent folder name is: " + fldr + "<br>"); // Print drive name. Response.Write("Contained on drive " + fldr.Drive + "<br>"); // Print root file name. if (fldr.IsRootFolder) Response.Write("This is the root folder."); else Response.Write("This folder isn't a root folder."); Response.Write("<br><br>"); // Create a new folder with the FileSystemObject object. fso.CreateFolder ("C:\\Bogus"); Response.Write("Created folder C:\\Bogus" + "<br>"); // Print the base name of the folder. Response.Write("Basename = " + fso.GetBaseName("c:\\bogus") + "<br>"); // Delete the newly created folder. fso.DeleteFolder ("C:\\Bogus"); Response.Write("Deleted folder C:\\Bogus" + "<br>"); } Microsoft® Scripting Library - FileSystemObject Working with Files Previous Next There are two major categories of file manipulation: Creating, adding, or removing data, and reading files Moving, copying, and deleting files Creating Files There are three ways to create an empty text file (sometimes referred to as a "text stream"). The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using this method in VBScript: Dim fso, f1 Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.CreateTextFile("c:\testfile.txt", True) To use this method in JScript, use this code: var fso, f1; fso = new ActiveXObject("Scripting.FileSystemObject"); f1 = fso.CreateTextFile("c:\\testfile.txt", true); View this sample code to see how the CreateTextFile method is used in FileSystemObject. The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set. In VBScript, the code looks like this example: Dim fso, ts Const ForWriting = 2 Set fso = CreateObject("Scripting. FileSystemObject") Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True) To create a text file using this method in JScript, use this code: var fso, ts; var ForWriting= 2; fso = new ActiveXObject("Scripting.FileSystemObject"); ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true); A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set. For this method, use the following code in VBScript: Dim fso, f1, ts Const ForWriting = 2 Set fso = CreateObject("Scripting.FileSystemObject") fso.CreateTextFile ("c:\test1.txt") Set f1 = fso.GetFile("c:\test1.txt") Set ts = f1.OpenAsTextStream(ForWriting, True) In JScript, use the code in the following example: var fso, f1, ts; var ForWriting = 2; fso = new ActiveXObject("Scripting.FileSystemObject"); fso.CreateTextFile ("c:\\test1.txt"); f1 = fso.GetFile("c:\\test1.txt"); ts = f1.OpenAsTextStream(ForWriting, true); Adding Data to the File Once the text file is created, add data to the file using the following three steps: 1. Open the text file. 2. Write the data. 3. Close the file. To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object. To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table. Task Method Write data to an open text file without a trailing newline character. Write Write data to an open text file with a trailing newline character. WriteLine Write one or more blank lines to an open text file. WriteBlankLines View this sample code to see how the Write, WriteLine, and WriteBlankLines methods are used in FileSystemObject. To close an open file, use the Close method of the TextStream object. View this sample code to see how the Close method is used in FileSystemObject. Note The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have such nonprinting characters. The following VBScript example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file: Sub CreateFile() Dim fso, tf Set fso = CreateObject("Scripting.FileSystemObject") Set tf = fso.CreateTextFile("c:\testfile.txt", True) ' Write a line with a newline character. tf.WriteLine("Testing 1, 2, 3.") ' Write three newline characters to the file. tf.WriteBlankLines(3) ' Write a line. tf.Write ("This is a test.") tf.Close End Sub This example demonstrates how to use the three methods in JScript: function CreateFile() { var fso, tf; fso = new ActiveXObject("Scripting.FileSystemObject"); tf = fso.CreateTextFile("c:\\testfile.txt", true); // Write a line with a newline character. tf.WriteLine("Testing 1, 2, 3.") ; // Write three newline characters to the file. tf.WriteBlankLines(3) ; // Write a line. tf.Write ("This is a test."); tf.Close(); } Reading Files To read data from a text file, use the Read , ReadLine, or ReadAll method of the TextStream object. The following table describes which method to use for various tasks. Task Method Read a specified number of characters from a file. Read Read an entire line (up to, but not including, the newline character). ReadLine Read the entire contents of a text file. ReadAll View this sample code to see how the ReadAll and ReadLine methods are used in FileSystemObject. If you use the Read or ReadLine method and want to skip to a particular portion of data, use the Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be displayed in a control, parsed by string functions (such as Left, Right, and Mid), concatenated, and so forth. The following VBScript example demonstrates how to open a file, write to it, and then read from it: Sub ReadFiles Dim fso, f1, ts, s Const ForReading = 1 Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.CreateTextFile("c:\testfile.txt", True) ' Write a line. Response.Write "Writing file <br>" f1.WriteLine "Hello World" f1.WriteBlankLines(1) f1.Close ' Read the contents of the file. Response.Write "Reading file <br>" Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading) s = ts.ReadLine Response.Write "File contents = '" & s & "'" ts.Close End Sub This code demonstrates the same thing in JScript: function ReadFiles() { var fso, f1, ts, s; var ForReading = 1; fso = new ActiveXObject("Scripting.FileSystemObject"); f1 = fso.CreateTextFile("c:\\testfile.txt", true); // Write a line. Response.Write("Writing file <br>"); f1.WriteLine("Hello World"); f1.WriteBlankLines(1); f1.Close(); // Read the contents of the file. Response.Write("Reading file <br>"); ts = fso.OpenTextFile("c:\\testfile.txt", ForReading); s = ts.ReadLine(); Response.Write("File contents = '" + s + "'"); ts.Close(); } Moving, Copying, and Deleting Files The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table. Task Method Move a file File.Move or FileSystemObject.MoveFile Copy a file File.Copy or FileSystemObject.CopyFile Delete a file File.Delete or FileSystemObject.DeleteFile View this sample code to see two ways to delete a file in FileSystemObject. The following VBScript example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both directories. To run the following example, create directories named \tmp and \temp in the root directory of drive C: Sub ManipFiles Dim fso, f1, f2, s Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.CreateTextFile("c:\testfile.txt", True) Response.Write "Writing file <br>" ' Write a line. f1.Write ("This is a test.") ' Close the file to writing. f1.Close Response.Write "Moving file to c:\tmp <br>" ' Get a handle to the file in root of C:\. Set f2 = fso.GetFile("c:\testfile.txt") ' Move the file to \tmp directory. f2.Move ("c:\tmp\testfile.txt") Response.Write "Copying file to c:\temp <br>" ' Copy the file to \temp. f2.Copy ("c:\temp\testfile.txt") Response.Write "Deleting files <br>" ' Get handles to files' current location. Set f2 = fso.GetFile("c:\tmp\testfile.txt") Set f3 = fso.GetFile("c:\temp\testfile.txt") ' Delete the files. f2.Delete f3.Delete Response.Write "All done!" End Sub This code shows the same thing in JScript: function ManipFiles() { var fso, f1, f2, s; fso = new ActiveXObject("Scripting.FileSystemObject"); f1 = fso.CreateTextFile("c:\\testfile.txt", true); Response.Write("Writing file <br>"); // Write a line. f1.Write("This is a test."); // Close the file to writing. f1.Close(); Response.Write("Moving file to c:\\tmp <br>"); // Get a handle to the file in root of C:\. f2 = fso.GetFile("c:\\testfile.txt"); // Move the file to \tmp directory. f2.Move ("c:\\tmp\\testfile.txt"); Response.Write("Copying file to c:\\temp <br>"); // Copy the file to \temp. f2.Copy ("c:\\temp\\testfile.txt"); Response.Write("Deleting files <br>"); // Get handles to files' current location. f2 = fso.GetFile("c:\\tmp\\testfile.txt"); f3 = fso.GetFile("c:\\temp\\testfile.txt"); // Delete the files. f2.Delete(); f3.Delete(); Response.Write("All done!"); } Microsoft® Scripting Library - FileSystemObject FileSystemObject Sample Code Previous The sample code described in this section provides a real-world example that demonstrates many of the features available in the FileSystemObject object model. This code shows how all the features of the object model work together, and how to use those features effectively in your own code. Note that since this code is fairly generic, some additional code and a little tweaking are needed to make this code actually run on your machine. These changes are necessary because of the different ways input and output to the user is handled between Active Server Pages and the Windows Scripting Host. To run this code on an Active Server Page, use the following steps: 1. 2. 3. 4. Create a standard Web page with an .asp extension. Copy the following sample code into that file between the &ltBODY>...</BODY> tags. Enclose all the code within <%...%> tags. Move the Option Explicit statement from its current position in the code to the very top of your HTML page, positioning it even before the opening <HTML> tag. 5. Place <%...%> tags around the Option Explicit statement to ensure that it's run on the server side. 6. Add the following code to the end of the sample code: Sub Print(x) Response.Write "<PRE>&ltFONT FACE=""Courier New"" SIZE=""1"">" Response.Write x Response.Write "</FONT></PRE>" End Sub Main The previous code adds a print procedure that will run on the server side, but display results on the client side. To run this code on the Windows Scripting Host, add the following code to the end of the sample code: Sub Print(x) WScript.Echo x End Sub Main The code is contained in the following section: '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' FileSystemObject Sample Code ' ' Copyright 1998 Microsoft Corporation. All Rights Reserved. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Option Explicit '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' Regarding code quality: ' ' 1) The following code does a lot of string manipulation by concatenating short ' strings together with the "&" operator. Since string concatenation ' is expensive, this is a very inefficient way to write code. However, it is a very ' maintainable way to write code, and is used here because this program performs extensive ' disk operations, and because the disk is much slower than the memory operations required to ' concatenate the strings. Keep in mind that this is demonstration code, not production code. ' ' 2) "Option Explicit" is used, because declared variable access is slightly faster than ' undeclared variable access. It also prevents bugs from creeping into your code, such as ' when you misspell DriveTypeCDROM as DriveTypeCDORM. ' ' 3) Error handling is absent from this code, to make the code more readable. Although ' precautions have been taken to ensure that the code will not error in common cases, file ' systems can be unpredictable. In production code, use On Error Resume Next and the ' Err object to trap possible errors. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' Some handy global variables ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Dim TabStop Dim NewLine Const TestDrive = "C" Const TestFilePath = "C:\Test" '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' Constants returned by Drive.DriveType ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Const Const Const Const Const DriveTypeRemovable = 1 DriveTypeFixed = 2 DriveTypeNetwork = 3 DriveTypeCDROM = 4 DriveTypeRAMDisk = 5 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' Constants returned by File.Attributes ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Const Const Const Const Const Const Const Const Const FileAttrNormal = 0 FileAttrReadOnly = 1 FileAttrHidden = 2 FileAttrSystem = 4 FileAttrVolume = 8 FileAttrDirectory = 16 FileAttrArchive = 32 FileAttrAlias = 64 FileAttrCompressed = 128 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' Constants for opening files ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Const OpenFileForReading = 1 Const OpenFileForWriting = 2 Const OpenFileForAppending = 8 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' ShowDriveType ' ' Purpose: ' ' Generates a string describing the drive type of a given Drive object. ' ' Demonstrates the following ' ' - Drive.DriveType ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function ShowDriveType(Drive) Dim S Select Case Drive.DriveType Case DriveTypeRemovable S = "Removable" Case DriveTypeFixed S = "Fixed" Case DriveTypeNetwork S = "Network" Case DriveTypeCDROM S = "CD-ROM" Case DriveTypeRAMDisk S = "RAM Disk" Case Else S = "Unknown" End Select ShowDriveType = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' ShowFileAttr ' ' Purpose: ' ' Generates a string describing the attributes of a file or folder. ' ' Demonstrates the following ' ' - File.Attributes ' - Folder.Attributes ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function ShowFileAttr(File) ' File can be a file or folder Dim S Dim Attr Attr = File.Attributes If Attr = 0 Then ShowFileAttr = "Normal" Exit Function End If If If If If If If If If Attr Attr Attr Attr Attr Attr Attr Attr And And And And And And And And FileAttrDirectory FileAttrReadOnly FileAttrHidden FileAttrSystem FileAttrVolume FileAttrArchive FileAttrAlias FileAttrCompressed Then Then Then Then Then Then Then Then S S S S S S S S = = = = = = = = S S S S S S S S & & & & & & & & "Directory " "Read-Only " "Hidden " "System " "Volume " "Archive " "Alias " "Compressed " ShowFileAttr = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GenerateDriveInformation ' ' Purpose: ' ' Generates a string describing the current state of the available drives. ' ' Demonstrates the following ' ' - FileSystemObject.Drives ' - Iterating the Drives collection ' - Drives.Count ' - Drive.AvailableSpace ' - Drive.DriveLetter ' - Drive.DriveType ' - Drive.FileSystem ' - Drive.FreeSpace ' - Drive.IsReady ' - Drive.Path ' - Drive.SerialNumber ' - Drive.ShareName ' - Drive.TotalSize ' - Drive.VolumeName ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GenerateDriveInformation(FSO) Dim Drives Dim Drive Dim S Set Drives = FSO.Drives S = "Number of drives:" & TabStop & Drives.Count & NewLine & NewLine ' S S S S S S Construct 1st line of report. = S & String(2, TabStop) & "Drive" = S & String(3, TabStop) & "File" = S & TabStop & "Total" = S & TabStop & "Free" = S & TabStop & "Available" = S & TabStop & "Serial" & NewLine ' S S S S S S S S S S Construct 2nd line of report. = S & "Letter" = S & TabStop & "Path" = S & TabStop & "Type" = S & TabStop & "Ready?" = S & TabStop & "Name" = S & TabStop & "System" = S & TabStop & "Space" = S & TabStop & "Space" = S & TabStop & "Space" = S & TabStop & "Number" & NewLine ' Separator line. S = S & String(105, "-") & NewLine For Each Drive In Drives S S S S = = = = S S S S & & & & Drive.DriveLetter TabStop & Drive.Path TabStop & ShowDriveType(Drive) TabStop & Drive.IsReady If Drive.IsReady Then If DriveTypeNetwork = Drive.DriveType Then S = S & TabStop & Drive.ShareName Else S = S & TabStop & Drive.VolumeName End If S = S & TabStop & Drive.FileSystem S = S & TabStop & Drive.TotalSize S = S & TabStop & Drive.FreeSpace S = S & TabStop & Drive.AvailableSpace S = S & TabStop & Hex(Drive.SerialNumber) End If S = S & NewLine Next GenerateDriveInformation = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GenerateFileInformation ' ' Purpose: ' ' Generates a string describing the current state of a file. ' ' Demonstrates the following ' ' - File.Path ' - File.Name ' - File.Type ' - File.DateCreated ' - File.DateLastAccessed ' - File.DateLastModified ' - File.Size ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GenerateFileInformation(File) Dim S S S S S S S S S = = = = = = = = NewLine & "Path:" & TabStop & File.Path S & NewLine & "Name:" & TabStop & File.Name S & NewLine & "Type:" & TabStop & File.Type S & NewLine & "Attribs:" & TabStop & ShowFileAttr(File) S & NewLine & "Created:" & TabStop & File.DateCreated S & NewLine & "Accessed:" & TabStop & File.DateLastAccessed S & NewLine & "Modified:" & TabStop & File.DateLastModified S & NewLine & "Size" & TabStop & File.Size & NewLine GenerateFileInformation = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GenerateFolderInformation ' ' Purpose: ' ' Generates a string describing the current state of a folder. ' ' Demonstrates the following ' ' - Folder.Path ' - Folder.Name ' - Folder.DateCreated ' - Folder.DateLastAccessed ' - Folder.DateLastModified ' - Folder.Size ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GenerateFolderInformation(Folder) Dim S S S S S S S S = = = = = = = "Path:" & TabStop & Folder.Path S & NewLine & "Name:" & TabStop & Folder.Name S & NewLine & "Attribs:" & TabStop & ShowFileAttr(Folder) S & NewLine & "Created:" & TabStop & Folder.DateCreated S & NewLine & "Accessed:" & TabStop & Folder.DateLastAccessed S & NewLine & "Modified:" & TabStop & Folder.DateLastModified S & NewLine & "Size:" & TabStop & Folder.Size & NewLine GenerateFolderInformation = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GenerateAllFolderInformation ' ' Purpose: ' ' Generates a string describing the current state of a ' folder and all files and subfolders. ' ' Demonstrates the following ' ' - Folder.Path ' - Folder.SubFolders ' - Folders.Count ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GenerateAllFolderInformation(Folder) Dim Dim Dim Dim Dim S SubFolders SubFolder Files File S = "Folder:" & TabStop & Folder.Path & NewLine & NewLine Set Files = Folder.Files If 1 = Files.Count Then S = S & "There is 1 file" & NewLine Else S = S & "There are " & Files.Count & " files" & NewLine End If If Files.Count <> 0 Then For Each File In Files S = S & GenerateFileInformation(File) Next End If Set SubFolders = Folder.SubFolders If 1 = SubFolders.Count Then S = S & NewLine & "There is 1 sub folder" & NewLine & NewLine Else S = S & NewLine & "There are " & SubFolders.Count & " sub folders" & NewLine & NewLine End If If SubFolders.Count <> 0 Then For Each SubFolder In SubFolders S = S & GenerateFolderInformation(SubFolder) Next S = S & NewLine For Each SubFolder In SubFolders S = S & GenerateAllFolderInformation(SubFolder) Next End If GenerateAllFolderInformation = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GenerateTestInformation ' ' Purpose: ' ' Generates a string describing the current state of the C:\Test ' folder and all files and subfolders. ' ' Demonstrates the following ' ' - FileSystemObject.DriveExists ' - FileSystemObject.FolderExists ' - FileSystemObject.GetFolder ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GenerateTestInformation(FSO) Dim TestFolder Dim S If Not FSO.DriveExists(TestDrive) Then Exit Function If Not FSO.FolderExists(TestFilePath) Then Exit Function Set TestFolder = FSO.GetFolder(TestFilePath) GenerateTestInformation = GenerateAllFolderInformation(TestFolder) End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' DeleteTestDirectory ' ' Purpose: ' ' Cleans up the test directory. ' ' Demonstrates the following ' ' - FileSystemObject.GetFolder ' - FileSystemObject.DeleteFile ' - FileSystemObject.DeleteFolder ' - Folder.Delete ' - File.Delete ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Sub DeleteTestDirectory(FSO) Dim TestFolder Dim SubFolder Dim File ' Two ways to delete a file: FSO.DeleteFile(TestFilePath & "\Beatles\OctopusGarden.txt") Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt") File.Delete ' Two ways to delete a folder: FSO.DeleteFolder(TestFilePath & "\Beatles") FSO.DeleteFile(TestFilePath & "\ReadMe.txt") Set TestFolder = FSO.GetFolder(TestFilePath) TestFolder.Delete End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' CreateLyrics ' ' Purpose: ' ' Builds a couple of text files in a folder. ' ' ' Demonstrates the following ' ' - FileSystemObject.CreateTextFile ' - TextStream.WriteLine ' - TextStream.Write ' - TextStream.WriteBlankLines ' - TextStream.Close ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Sub CreateLyrics(Folder) Dim TextStream Set TextStream = Folder.CreateTextFile("OctopusGarden.txt") TextStream.Write("Octopus' Garden ") ' Note that this does not add a line feed to the file. TextStream.WriteLine("(by Ringo Starr)") TextStream.WriteBlankLines(1) TextStream.WriteLine("I'd like to be under the sea in an octopus' garden in the shade,") TextStream.WriteLine("He'd let us in, knows where we've been -- in his octopus' garden in the shade.") TextStream.WriteBlankLines(2) TextStream.Close Set TextStream = Folder.CreateTextFile("BathroomWindow.txt") TextStream.WriteLine("She Came In Through The Bathroom Window (by Lennon/McCartney)") TextStream.WriteLine("") TextStream.WriteLine("She came in through the bathroom window protected by a silver spoon") TextStream.WriteLine("But now she sucks her thumb and wanders by the banks of her own lagoon") TextStream.WriteBlankLines(2) TextStream.Close End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' GetLyrics ' ' Purpose: ' ' Displays the contents of the lyrics files. ' ' ' Demonstrates the following ' ' - FileSystemObject.OpenTextFile ' - FileSystemObject.GetFile ' - TextStream.ReadAll ' - TextStream.Close ' - File.OpenAsTextStream ' - TextStream.AtEndOfStream ' - TextStream.ReadLine ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GetLyrics(FSO) Dim TextStream Dim S Dim File ' There are several ways to open a text file, and several ways to read the ' data out of a file. Here's two ways to do each: Set TextStream = FSO.OpenTextFile(TestFilePath & "\Beatles\OctopusGarden.txt", OpenFileForReading) S = TextStream.ReadAll & NewLine & NewLine TextStream.Close Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt") Set TextStream = File.OpenAsTextStream(OpenFileForReading) Do While Not TextStream.AtEndOfStream S = S & TextStream.ReadLine & NewLine Loop TextStream.Close GetLyrics = S End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' BuildTestDirectory ' ' Purpose: ' ' Builds a directory hierarchy to demonstrate the FileSystemObject. ' ' We'll build a hierarchy in this order: ' ' C:\Test ' C:\Test\ReadMe.txt ' C:\Test\Beatles ' C:\Test\Beatles\OctopusGarden.txt ' C:\Test\Beatles\BathroomWindow.txt ' ' ' Demonstrates the following ' ' - FileSystemObject.DriveExists ' - FileSystemObject.FolderExists ' - FileSystemObject.CreateFolder ' - FileSystemObject.CreateTextFile ' - Folders.Add ' - Folder.CreateTextFile ' - TextStream.WriteLine ' - TextStream.Close ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function BuildTestDirectory(FSO) Dim TestFolder Dim SubFolders Dim SubFolder Dim TextStream ' Bail out if (a) the drive does not exist, or if (b) the directory being built ' already exists. If Not FSO.DriveExists(TestDrive) Then BuildTestDirectory = False Exit Function End If If FSO.FolderExists(TestFilePath) Then BuildTestDirectory = False Exit Function End If Set TestFolder = FSO.CreateFolder(TestFilePath) Set TextStream = FSO.CreateTextFile(TestFilePath & "\ReadMe.txt") TextStream.WriteLine("My song lyrics collection") TextStream.Close Set SubFolders = TestFolder.SubFolders Set SubFolder = SubFolders.Add("Beatles") CreateLyrics SubFolder BuildTestDirectory = True End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' ' The main routine ' ' First, it creates a test directory, along with some subfolders and files. ' Then, it dumps some information about the available disk drives and ' about the test directory, and then cleans everything up again. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Sub Main Dim FSO ' Set up global data. TabStop = Chr(9) NewLine = Chr(10) Set FSO = CreateObject("Scripting.FileSystemObject") If Not BuildTestDirectory(FSO) Then Print "Test directory already exists or cannot be created. Cannot continue." Exit Sub End If Print GenerateDriveInformation(FSO) & NewLine & NewLine Print GenerateTestInformation(FSO) & NewLine & NewLine Print GetLyrics(FSO) & NewLine & NewLine DeleteTestDirectory(FSO) End Sub ...
View Full Document

Ask a homework question - tutors are online