JavaScriptä¸çåºæ¬æ¸å¸ - æ¸ååéç®ç¬¦
卿¬èª²ç¨çéä¸é»ä¸ï¼æåå°è¨è« JavaScript ä¸çæ¸å¸ - æåå¦ä½ä½¿ç¨operators åå ¶ä»åè½ä¾æåæç¸±æ¸åä¾é²è¡æåçåºå¹ã
| å åç¥è: | é»è ¦åºç¤ç¥èï¼äºè§£åºæ¬ç HTML å CSS ï¼äºè§£ JavaScript æ¯ä»éº¼ã |
|---|---|
| ç®æ¨: | çæJavaScriptä¸çåºç¤æ¸å¸ã |
æ¯å人é½åæ¡æ¸å¸
好å§ï¼ä¹è¨±ä¸æ¯ã æåä¸çä¸äºäººåæ¡æ¸å¸ï¼æåæäºäººè¨åæ¸å¸ï¼å çºæåå¿ é å¨å¸æ ¡å¸ç¿ä¹æ³å餿³ï¼èæåä¸çä¸äºäººå ©è çè¦ã 使åé½ä¸è½å¦èªæ¸å¸æ¯çæ´»ä¸çä¸ååºæ¬çµæé¨åï¼æåé¢ä¸éå®åã ç¶æåå¸ç¿ JavaScriptï¼æä»»ä½å ¶ä»èªè¨ï¼çç¨å¼æï¼å°¤å ¶å¦æ¤ - æåæåçå¾å¤äºæ é½ä¾è³´æ¼èçæ¸å¼æ¸æï¼è¨ç®æ°å¼ççï¼ä½ 䏿é©è¨å¸ç¿ JavaScript æä¸å¥åè½é½å ¨çæ¸å¸å½æ¸ã
æ¬æå è¨è«ä½ ç¾å¨éäºè§£çåºæ¬é¨åã
æ¸åç種é¡
å¨ç¨å¼è£¡ï¼å³ä½¿ç¾æå¨ç¥çåé²ä½æ¸åç³»çµ±ä¹æ¯ä½ æ³åçè¦è¤éãæå使ç¨ä¸åçè¡èªä¾æè¿°ä¸åé¡åçåé²ä½æ¸åï¼ä¾å¦ï¼
- Integers æ¯æ´æ¸ï¼å¦ï¼10ï¼400ï¼æ -5ã
- Floating point numbers (floats) æµ®é»æ¸å ·æå°æ¸é»è·å°æ¸ä½ï¼ä¾å¦ 12.5 å 56.7786543ã
- Doubles æ¯ä¸ç¨®ç¹å®åæ çæµ®é»æ¸ that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
æåçè³æä¸åé¡åçè碼系統ï¼åé²ä½ä»¥ 10 çºå®ä½ï¼è¡¨ç¤ºæ¯åä½¿ç¨ 0â9ï¼ï¼ä½æ¯ä¹æåéäºï¼
- äºé²ä½ âè¨ç®æ©çæåºå±¤èªè¨ï¼0 å 1ã
- å «é²ä½ â以 8 çºå®ä½ï¼æ¯åä½¿ç¨ 0â7ã
- åå é²ä½ â以 16 çºå®ä½ï¼å¨æ¯åä¸ä½¿ç¨ 0â9ï¼ç¶å¾ä½¿ç¨ aâfãä½ ä¹åå¨ CSS ä¸è¨ç½®é¡è²æï¼å¯è½å·²ç¶éå°ééäºæ¸åã
**å¨éå§æå¿å¤§è ¦èåä¹åï¼å ççï¼**é¦å ï¼æåå°å¨æ´å課ç¨ä¸å®å ¨ä½¿ç¨åé²ä½æ¸ï¼ä½ å¾å°ææ³å°å ¶ä»é¡åçéæ±ï¼å¦ææç話ã
第äºåå¥½æ¶æ¯æ¯ JavaScript åªæä¸ç¨®æ¸åè³æé¡å ï¼çå°äºï¼å°±æ¯Numberãé代表ç¡è«ä½ å¨ JavaScript éè¦èçåªç¨®æ¸åï¼èçæ¹æ³é½æ¯ä¸æ¨£çã
å註ï¼äºå¯¦ä¸, JavaScript æç¬¬äºç¨®æ¸ååæ
ï¼ BigInt, ç¨æ¼é常ãé常ãéå¸¸å¤§çæ´æ¸ãä½éç¯èª²æåªéè¦æå¿ Number çå¼ã
ææéº¼ç齿¯äºæ¸å!
è®æåä¾å¿«éæä½ä¸äºæ¸åä¾éæ°èªèä¸ä¸æåæéè¦ç¨å°çåºæ¬èªæ³ãå°ä¸é¢çéæ±è¡¨è¼¸å ¥é²ä½ çéç¼è å·¥å · js æ§å¶å°(developer tools JavaScript console)ï¼ææ¯ç°¡å®å»ºç«å¨ä»»ä½ä½ åå¥½çæ§å¶å°ã
-
é¦å ï¼å ä¾å®£åå ©åè®æ¸ï¼ä¸¦åå¥è³¦äºä»ååå§å¼çºæ´æ¸èæµ®é»æ¸ï¼ç¶å¾æ¥èæä¸è®æ¸å稱ä¾ç¢ºèªè¬äºé å:
jsvar myInt = 5; var myFloat = 6.667; myInt; myFloat; -
æ¸åçå¼ä¸éè¦å¼èæ¡èµ·ä¾ â 試è宣ååè³¦äºæ´å¤åå§å¼çºæ¸åçè®æ¸ï¼å¨ç¹¼çºä¸å»ä¹åã
-
ç¾å¨ï¼ä¾ç¢ºèª Now let's check that both our original variables are of the same datatype. There is an operator called
typeofin JavaScript that does this. Enter the below two lines as shown:jstypeof myInt; typeof myFloat;You should get
"number"returned in both cases â this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. Phew!
ç®è¡éç®ç¬¦
Arithmetic operators are the basic operators that we use to do sums:
| Operator | Name | Purpose | Example |
|---|---|---|---|
+ |
å æ³ | Adds two numbers together. | 6 + 9 |
- |
æ¸æ³ | Subtracts the right number from the left. | 20 - 15 |
* |
乿³ | Multiplies two numbers together. | 3 * 7 |
/ |
餿³ | Divides the left number by the right. | 10 / 5 |
% |
餿¸ (sometimes called modulo) |
Returns the remainder left over after you've divided the left number into a number of integer portions equal to the right number. |
8 % 3 (returns 2, as three goes into 8 twice, leaving 2
left over.)
|
| ** | ææ¸ |
Raises a base number to the exponent power,
that is, the base number multiplied by itself,
exponent times. It was first Introduced in EcmaScript 2016.
|
5 ** 2 (5ç2次æ¹å¾ 25ï¼è·
5 * 5çµæç¸å)
|
å註ï¼You'll sometimes see numbers involved in sums referred to as operands.
åè¨»ï¼ You may sometimes see exponents expressed using the older Math.pow() method, which works in a very similar way. For example, in Math.pow(7, 3), 7 is the base and 3 is the exponent, so the result of the expression is 343. Math.pow(7, 3) is equivalent to 7**3.
We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your developer tools JavaScript console, or use the simple built in console seen earlier if you'd prefer, to familiarize yourself with the syntax.
-
First try entering some simple examples of your own, such as
js10 + 7; 9 * 8; 60 % 3; -
You can also try declaring and initializing some numbers inside variables, and try using those in the sums â the variables will behave exactly like the values they hold for the purposes of the sum. For example:
jsvar num1 = 10; var num2 = 50; 9 * num1; num2 / num1; -
Last for this section, try entering some more complex expressions, such as:
js5 + 10 * 3; (num2 % 9) * num1; num2 + num1 / 8 + 2;
Some of this last set of sums might not give you quite the result you were expecting; the below section might well give the answer as to why.
Operator precedence
Let's look at the last example from above, assuming that num2 holds the value 50 and num1 holds the value 10 (as originally stated above):
num2 + num1 / 8 + 2;
As a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10 equals 6".
But the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25".
This is because of operator precedence â some operators will be applied before others when calculating the result of a sum (referred to as an expression, in programming). Operator precedence in JavaScript is the same as is taught in math classes in school â Multiply and divide are always done first, then add and subtract (the sum is always evaluated from left to right).
If you want to override operator precedence, you can put parentheses round the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this:
(num2 + num1) / (8 + 2);
Try it and see.
å註ï¼A full list of all JavaScript operators and their precedence can be found in Expressions and operators.
éå¢å鿏éç®ç¬¦
Sometimes you'll want to repeatedly add or subtract one to/from a numeric variable value. This can be conveniently done using the increment (++) and decrement(--) operators. We used ++ in our "Guess the number" game back in our first splash into JavaScript article, when we added 1 to our guessCount variable to keep track of how many guesses the user has left after each turn.
guessCount++;
å註ï¼They are most commonly used in loops, which you'll learn about later on in the course. For example, say you wanted to loop through a list of prices, and add sales tax to each one. You'd use a loop to go through each value in turn and do the necessary calculation for adding the sales tax in each case. The incrementor is used to move to the next value when needed. We've actually provided a simple example showing how this is done â check it out live, and look at the source code to see if you can spot the incrementors! We'll look at loops in detail later on in the course.
Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return an error:
3++;
So, you can only increment an existing variable. Try this:
var num1 = 4;
num1++;
Okay, strangeness number 2! When you do this, you'll see a value of 4 returned â this is because the browser returns the current value, then increments the variable. You can see that it's been incremented if you return the variable value again:
num1;
The same is true of -- : try the following
var num2 = 6;
num2--;
num2;
å註ï¼You can make the browser do it the other way round â increment/decrement the variable then return the value â by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use ++num1 and --num2.
賦å¼éç®ç¬¦
Assignment operators are operators that assign a value to a variable. We have already used the most basic one, =, loads of times â it simply assigns the variable on the left the value stated on the right:
var x = 3; // x contains the value 3
var y = 4; // y contains the value 4
x = y; // x now contains the same value y contains, 4
But there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most common are listed below:
| Operator | Name | Purpose | Example | Shortcut for |
|---|---|---|---|---|
+= |
Addition assignment | Adds the value on the right to the variable value on the left, then returns the new variable value | x = 3; x += 4; |
x = 3; x = x + 4; |
-= |
Subtraction assignment | Subtracts the value on the right from the variable value on the left, and returns the new variable value | x = 6; x -= 3; |
x = 6; x = x - 3; |
*= |
Multiplication assignment | Multiples the variable value on the left by the value on the right, and returns the new variable value | x = 2; x *= 3; |
x = 2; x = x * 3; |
/= |
Division assignment | Divides the variable value on the left by the value on the right, and returns the new variable value | x = 10; x /= 5; |
x = 10; x = x / 5; |
Try typing some of the above examples into your console, to get an idea of how they work. In each case, see if you can guess what the value is before you type in the second line.
Note that you can quite happily use other variables on the right hand side of each expression, for example:
var x = 3; // x contains the value 3
var y = 4; // y contains the value 4
x *= y; // x now contains the value 12
å註ï¼There are lots of other assignment operators available, but these are the basic ones you should learn now.
Active learning: sizing a canvas box
In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the Canvas API. There is no need to worry about how this works â just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables x and y, which are initially both given a value of 50.
In the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. Let's try the following:
- Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator.
- Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and an arithmetic operator.
- Change the line that calculates x so the box is 250px wide, but the 250 is calculated using two numbers and the remainder (modulo) operator.
- Change the line that calculates y so the box is 150px high, but the 150 is calculated using three numbers and the subtraction and division operators.
- Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator.
- Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator.
Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.
æ¯è¼éç®ç¬¦
Sometimes we will want to run true/false tests, then act accordingly depending on the result of that test â to do this we use comparison operators.
| Operator | Name | Purpose | Example |
|---|---|---|---|
=== |
Strict equality | Tests whether the left and right values are identical to one another | 5 === 2 + 4 |
!== |
Strict-non-equality | Tests whether the left and right values not identical to one another | 5 !== 2 + 3 |
< |
Less than | Tests whether the left value is smaller than the right one. | 10 < 6 |
> |
Greater than | Tests whether the left value is greater than the right one. | 10 > 20 |
<= |
Less than or equal to | Tests whether the left value is smaller than or equal to the right one. | 3 <= 2 |
>= |
Greater than or equal to | Tests whether the left value is greater than or equal to the right one. | 5 >= 4 |
å註ï¼You may see some people using == and != in their tests for equality and non-equality. These are valid operators in JavaScript, but they differ from ===/!==. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them.
If you try entering some of these values in a console, you'll see that they all return true/false values â those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to:
- Display the correct text label on a button depending on whether a feature is turned on or off
- Display a game over message if a game is over or a victory message if the game has been won
- Display the correct seasonal greeting depending what holiday season it is
- Zoom a map in or out depending on what zoom level is selected
We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example:
<button>Start machine</button>
<p>The machine is stopped.</p>
var btn = document.querySelector("button");
var txt = document.querySelector("p");
btn.addEventListener("click", updateBtn);
function updateBtn() {
if (btn.textContent === "Start machine") {
btn.textContent = "Stop machine";
txt.textContent = "The machine has started!";
} else {
btn.textContent = "Start machine";
txt.textContent = "The machine is stopped.";
}
}
You can see the equality operator being used just inside the updateBtn() function. In this case, we are not testing if two mathemetical expressions have the same value â we are testing whether the text content of a button contains a certain string â but it is still the same principle at work. If the button is currently saying "Start machine" when it is pressed, we change its label to "Stop machine", and update the label as appropriate. If the button is currently saying "Stop machine" when it is pressed, we swap the display back again.
å註ï¼Such a control that swaps between two states is generally referred to as a toggle. It toggles between one state and another â light on, light off, etc.
Summary
In this article we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll see numbers used again and again, all the way through your JavaScript learning, so it's a good idea to get this out of the way now. If you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.
In the next article, we'll explore text and how JavaScript allows us to manipulate it.
å註ï¼If you do enjoy math and want to read more about how it is implemented in JavaScript, you can find a lot more detail in MDN's main JavaScript section. Great places to start are our Numbers and dates and Expressions and operators articles.