JavaScript Tutorial/Operators/Assignment

Материал из Web эксперт
Версия от 08:24, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Advanced Assignment Operators

Advanced assignment operators combine the basic assignment and other operators into one functional operator.

Operator Example Description += x+=y x = x + y; -= x-=y x = x - y;

  • =

x*=y x = x * y; /= x/=y x = x / y; %= x%=y x = x % y; <<= x<<=y x = x << y; >>= x>>=y x = x >> y; >>>= x>>>=y x = x >>> y; &= x&=y x = x & y; |= x|=y x = x | y; ^= x^=y x = x ^ y;

All the advanced assignment operators, except for +=, will attempt to convert strings to numbers.

If strings are used with the += operator, the left operand is concatenated to the end of the right operand.

The following example uses the Addition Operator to Perform String Concatenation.



<html>
<SCRIPT LANGUAGE="JavaScript">
<!--
    y = "A";
    y += "B";
    document.write("y= ",y);
-->
</SCRIPT>
</html>


Assignment by Value Versus by Reference

When the assignment operator works on primitive values (numbers, strings, Boolean, null, and undefined), a copy of the value is made.

When the assignment operator works on JavaScript objects, references to the objects are copied.



<html>
<SCRIPT LANGUAGE="JavaScript">
<!--
    var number1 = 9;
    var arrayOfNum1 = new Array(2,6);
    var number2 = number1;
    var arrayOfNum2 = arrayOfNum1;
    number2 = 2;
    arrayOfNum2[1] = 4;
    document.write("number1=",number1,"<BR>");
    document.write("number2=",number2,"<BR>");
    document.write("arrayOfNum1[0]=",arrayOfNum1[0],"<BR>");
    document.write("arrayOfNum1[1]=",arrayOfNum1[1],"<BR>");
    document.write("arrayOfNum2[0]=",arrayOfNum2[0],"<BR>");
    document.write("arrayOfNum2[1]=",arrayOfNum2[1],"<BR>");
-->
</SCRIPT>
</html>


Assignment operator

The basic format of the assignment operator is:



x = 6;


x *= 2 (Compound Multiply)

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 6;
alert(x *= 2);
//  -->
</script>
</head>
<body>
</body>
</html>


x += 2 (Compound Plus)

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 6;
alert(x += 2);
//  -->
</script>
</head>
<body>
</body>
</html>


x -= 2 (Compound Subtraction)

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 6;
alert(x -= 2);
//  -->
</script>
</head>
<body>
</body>
</html>


x /= 2 (Multiply Divide)

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 6;
alert(x /= 2);
//  -->
</script>
</head>
<body>
</body>
</html>