`
schy_hqh
  • 浏览: 558403 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

w3r-javascript05: Arithmetic Operators

 
阅读更多

 

Arithmetic Operators : +, -, *, /

In JavaScript, arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. There are four standard  arithmetic operators, addition (+), subtraction (-), multiplication (*), and division (/).

These operators work as they do in other programming languages except the division (/) operator which returns a floating-point division in JavaScript, not a truncated division as it does in languages such as C or Java.
 
For example: 
1/2  returns 0.5 in JavaScript.
1/2  returns 0 in Java.

In addition, JavaScript provides modules(%), increment(++), decrement(--) and unary negation(-) operators.

 

 

+ addition operator

 

HTML Code

<!doctype html>
<head>
<meta charset="utf-8">
<title>JavaScript + operator example</title>
<meta name="description" content="This document contains
an example of JavaScript + operator" />
</head>
<body>
<script src="addition_example1.js"></script>
</body>
</html>

 JS Code

var var1 = 45;
var var2 = 78;
var var3 = 45.10;
var var4 = 178.12;
var newvar  = var1 + var2;
var newvar1 = var3 + var4;
var newParagraph3 = document.createElement("p");
var newText3 = document.createTextNode("var1 + var2 = "+newvar+" and var3 + var4 = "+newvar1);
newParagraph3.appendChild(newText3);
document.body.appendChild(newParagraph3);

 

- subtraction operator

 

HTML Code

<!doctype html>
<head>
<meta charset="utf-8">
<title>JavaScript subtraction operator example </title>
<meta name="description" content="This document contains an
example Using JavaScript subtraction operator"/>
</head>
<script src="subtraction-example1.js"></script>
</body>
</html>

 

 JS Code

var var1 = 45;
var var2 = 78;
var str1 = "w3resource";
var str2 = ".com";
var newvar = var1 - var2;
var newstr = str1 - str2; //NAN
var varstr = var1 - str2; //NAN
var newParagraph = document.createElement("p");
var newText = document.createTextNode("var1 -var2 = "+ newvar);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);
var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode("str1 - str2  = "+ newstr);
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);
var newParagraph2 = document.createElement("p");
var newText2 = document.createTextNode("var1 - str2  = "+ varstr);
newParagraph2.appendChild(newText2);
document.body.appendChild(newParagraph2)

 

 

* multiplication operator

 

HTML Code

<!doctype html><head>
<meta charset="utf-8">
<title>JavaScript multiplication operator (*) example with DOM
</title>
<meta name="description" content="This document contains an example
Using JavaScript multiplication operator (*) with dom"/>
</head>
<body>
<script src="multiplication-example1.js"></script>
</body>
</html>

 

 

JS Code

var var1 = 45;
var var2 = 78;
var var3 = 45.10;
var var4 = 178.12;
var newvar  = var1 * var2;
var newvar1 = var3 * var4;

var newParagraph = document.createElement("p");
var newText = document.createTextNode("var1 * var2 = "+ newvar);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);

var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode("var3 * var4  = "+ newvar1);
newParagraph1.appendChild newText1);
document.body.appendChild(newParagraph1);

 

 

/ division operator 

HTML Code

<!doctype html>
<head>
<meta charset="utf-8">
<title>JavaScript / operator example </title>
<meta name="description" content="This document contains an example of JavaScript division operator" />
</style>
</head>
<body>
<script src="division-example1.js"></script>
</body>
</html> 

 

JS Code

var var1 = 45;
var var2 = 78;
var var3 = 1;
var var4 = 2;
var newvar  = var1 / var2; //0.5769230769230769
var newvar1 = var3 / var4; //0.5

var newParagraph = document.createElement("p");
var newText = document.createTextNode ("var1 / var2 = "+ newvar);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);

var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode("var3 / var4  = "+ newvar1);
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);

 

 

Arithmetic Special Operators (%, ++, --, - ) 

 

Assignment Operators(+=,-=,*=,/=,%=,<<=,>>=,>>>=,&=,^=,|=)

 

Bitwise Operators(a & b,a | b,a ^ b,~ a,a << b,a >> b,a >>> b)

 

Comparison Operators(==,===,!=,!==,>,>=,<,<=)

Equal (==)  

x == y  Returns true if the operands are equal.

var s1 = 300;
var s2 = '300';
alert(s1==s2);//true

 

Strict equal (===)

x === y  Returns true if the operands are equal and of the same type. 

var s1 = 300,
      s2 = '300',
      s3 = 300;
alert(s1===s2);//false
alert(s1===s3);//true

 

Not equal (!=)

x != y  Returns true if the operands are not equal.

var s1 = 300,
		s2 = '300',
		s3 = 500;
alert(s1!=s2);//false
alert(s1!=s3);//true

 

Strict not equal (!==)

x !== y  Returns true if the operands are not equal and/or not of the same type. 

var s1 = 300,
		s2 = '300',
		s3 = 500;
alert(s1!==s2);//true
alert(s1!==s3);//true

 

Greater than (>)

Greater than or equal (>=)

 

Less than (<)

Less than or equal (<=)

 

 

Logical Operators(&&, ||, !)

 

String Concatenation(+, +=)

 

Special Operators:

 

?: (Conditional operator)

Condition ? expr1 : expr2

status = (marks >= 30) ? "Pass" : "Fail"

 

Comma Operator

The comma operator (,) is used to execute two expressions sequentially.

 

expr1, expr2

 

We use the comma operator when we want to include multiple expressions in a location that requires a single expression.

This operator is generally used inside a for loop, to allow multiple variables to be updated (increase/decrease) each time through the loop.

For example we want to display a serial No. (starting from 1) and a employee code ( starting from 10 ), the following code uses the comma operator to increment two variables at once.

 

for (var i=1, j=10; i <=10; i++, j++)
{
alert('Sl. No. : '+i+' Employee Code : '+j)
} 

 

 

 

function Operator

The function operator defines a function inside an expression. 

var1 = function( parameter1, parameter2,......parametern)

 

{

statement(s)

}

var a = 12;
var b = 14;
var x = function(a,b)
{
return a*a+2*a*b+b*b;
};
alert("The square of "+a+ " and "+b +" is " +x(a,b));

 

 

 

in Operator

 

property in object  

判断某个属性是否在对象中存在

property : Name of the property.

object : Name of the object.

var employeeobj = {name:"Robert",designation:"Officer",age:"34"};
if ("designation" in employeeobj)
{
alert('Designation property is present'); //alert this
}
else
{
alert('Designation property is not present'); 
}

 

 

 

instanceof Operator

The instanceof operator is used to check the type of an object at run time. The instanceof operator returns a boolean value that indicates if an object is an instance of a particular class. 

 

var result = objectName instanceof objectType

 

var string1 = "w3resource"; //Declaring string object
var date1 = new Date();  //Declaring Date object
if (string1 instanceof String) 
{
var newParagraph = document.createElement("p");
var newText = document.createTextNode('The type of string1 object is String'); 
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph); 
}
if (date1 instanceof Date)
{
var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode('The type of date1 object is Date'); 
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);
}

 

 

new Operator

The new operator is used to create an instance of a user defined object type or one of builtin object types which has a constructor function.

 

var objectName = new objectType(param1, param2, ...., paramN); 

 

 To create an user defined object type following steps are required. 

Write a function to define the object type  写一个函数来定义一个对象类型

Use new operator to create an instance of the object.   使用new操作符创建这个对象的实例

 

 

Suppose we want to create an object type for students with three properties name, class and rollno. To do this first declare the following function. 

  function student(name, class, rollno)
    { 
    this.name = name;
    this.class = class 
    this.rollno = rollno;
    } 

 

使用new关键字完成对象的创建

studentv = new student("John", "V", 10)

studentvi = new student("David Rayy", "VI", 12)

 

  function school(sname,  city, stus)
    { 
    this.sname = sname;
    this.city = city;
    this.stus = stus;
    } 

 

var stus = new Array(studentv,studentvi);

school = new school("Dubai International School", "Dubai", stus);

 

 

 

this Operator

The this operator is used to refer the current object. In general, this refers to the calling object in a method. 

In the following web document this operator is used as internal reference property of the form instances.

<!doctype html>
<head>
<meta charset="utf-8">
<title>JavaScript this operator example with DOM
</title>
<meta name="description" content="This document contains an
example of JavaScript this operator"/>
</head>
<body>
<form name="myform" action="#">
<input type="text" value="Text Here" name="text1" />
<input type= "submit" value="Submit" name="mysubmit" onclick=
"formdetails(this.form)" />
</form>
<script src="javascript-this-operator-example1.js">
</script>
</body>
</html>

 

 //this ---> form
function formdetails(form)
{

var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("The name of the form is: "+form.name); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph);


var newParagraph1 = document.createElement("p"); 
var newText1 = document.createTextNode("The
deault value of text box is: "+form.text1.value);  newParagraph1.appendChild(newText1); 
document.body.appendChild(newParagraph1);


var newParagraph2 = document.createElement("p");
var newText2 = document.createTextNode("The name
of the submit button box is: "+form.mysubmit.name); newParagraph2.appendChild(newText2);
document.body.appendChild(newParagraph2);

var newParagraph3 = document.createElement("p"); 
var newText3 = document.createTextNode("The deault
value of submit button is: "+form.mysubmit.value);
newParagraph3.appendChild(newText3);
document.body.appendChild(newParagraph3);

}

 

 

typeof operator

The typeof operator is used to get the data type (returns a string) of its operand.

The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type. 

 

返回值:字符串

"object","boolean","function","number","string","undefined"

 

Examples of typeof operator : string

typeof ""
typeof "abc"
typeof (typeof 1)

 

Examples of typeof operator : number

typeof 17
typeof -14.56
typeof 4E-3
typeof Infinity
typeof Math.LN2
typeof NaN

 

Examples of typeof operator : boolean

typeof false
typeof true

 

Examples of typeof operator : function

typeof Math.tan
typeof function(){}

 

 

Examples of typeof operator : object

typeof {a:1}
typeof new Date()
typeof null
typeof /a-z/
typeof Math
typeof JSON

 

 

Examples of typeof operator : undefined

typeof undefined
typeof abc

 

More examples on typeof operator

typeof(4+7); //returns number typeof("4"+"7"); //returns string typeof(4*"7"); //returns number
typeof(4+"7"); //returns string

 

What is the difference between typeof myvar and typeof(myvar) in JavaScript? 

No difference!

 

How to detect an undefined object property in JavaScript?

var index = 8;
  var result = (typeof index === 'number');
  alert(result);
  // Output: true
var description = "w3resource";
  var result = (typeof description === 'string');
  alert(result); 
  // Output: true 

 

 

void operator

The void operator is used to evaluate a JavaScript expression without returning a value. 

 

The following web document shows how the void operator is used.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript void operator example</title>
</head>
<body>
<a href="javascript:void(alert('Thank you.'))">Click here to see a message</a>
</body>
</html>

 

In the following web document void operator is used to call a function. 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript void operator (calling function) example</title>
</head>
<body>
<script type="text/javascript">
function testfunc(){document.write("good!");}
</script>
<a href="javascript:void(testfunc())">
Click here to call testfunc()</a>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    高考英语单词分类记忆.doc

    - Arithmetic:算术 - Geometry:几何 - statistics:统计学 - physics:物理 - chemistry:化学 - Chinese:汉语 - biology:生物 - politics:政治 - history:历史 - geography:地理 - physical education (PE)...

    数学的英语单词(.doc

    - Arithmetic Progression: 等差数列 - Arm: 股(直角三角形的) - Average: 平均值 - Base: 底 - Be Contained In: 在...之中 - Bisect: 平分 - Center: 中心 - Chord: 弦 - Circle: 圆 - Circumference:...

    GRE考试数学英文词汇

    - 复利:Compound Interest(A=P(1+R/n)^(nt)) 以上列出的词汇和公式是GRE数学部分的基础,掌握这些词汇和相关的数学概念对于在考试中取得好成绩是必须的。复习时,建议考生不仅要记住这些词汇,而且要理解它们的...

    babel-plugin-precise-arithmetic::electric_plug:一款babel plugin 用于在编译时对 js 浮点数四则运算产生的精度问题做统一处理

    npm install babel-plugin-precise-arithmetic --save-dev 添加babel-plugin-精确算法 .babelrc { " plugins " : [ " precise-arithmetic " ] } 或者 webpack.config.js ... { test : / \. js $ / , loader : ...

    fluent-plugin-simplearithmetic:用于计算消息的 Fluent 插件

    安装 $ fluent-gem install fluent-plugin-simplearithmetic教程假设你有这样的消息: { 'apple': 7, 'orange': 3, 'time_start': '2001-02-03T04:05:06Z', 'time_finish': '2001-02-03T04:06:12Z',}现在您可以使用...

    Context-Based Adaptive Binary Arithmetic Coding in the H.264 AVC Video Compression Standard

    基于上下文的自适应二进制算术编码(Context-Based Adaptive Binary Arithmetic Coding,简称CABAC)是新的ITU-T/ISO/IEC视频编码标准H.264/AVC中的两种熵编码方法之一。该算法最初在[7]中以初级形式被引入,并经过...

    PremiereCS3视频特效中英文对照

    - Compound arithmetic:复合数学运算,结合多个通道进行运算。 - Invert:反向/倒置,将图像颜色反转。 - Set matte:设置磨砂,用于创建遮罩或合成效果。 - Solid composite:完全复合,通过混合模式和颜色...

    matlab的学习

    2.1 算术运算符(Arithmetic operators) 这些是进行基本数学运算的符号。 - *:矩阵乘法。 - .*:数组元素间的乘法。 - ^:矩阵的幂运算。 - .^:数组的幂运算。 - \、/:左除和右除运算。 - ./、.\:数组...

    arithmetic-formatter-freecodecamp:FreeCodeCamp-使用Python项目#1进行科学计算

    算术格式化程序免费代码营 FreeCodeCamp-使用Python项目#1进行科学计算 任务 小学学生通常会垂直排列算术问题,以使其更容易解决。 例如,“ 235 + 52”变为: 235 + 52 ----- ... arithmetic_arra

    《计算机组成原理》唐朔飞第二版课后答案.pdf

    - ALU:Arithmetic Logic Unit,算术逻辑单元。 - ACC:Accumulator,累加器。 - MQ:Multiplier-Quotient Register,乘商寄存器。 - X:在此表示操作数寄存器。 - MAR:Memory Address Register,存储器地址...

    Comman_Arithmetic_Lib常用算法程序集

    "Comman_Arithmetic_Lib常用算法程序集" 是一个专门收集各种常用算法程序的资源库,它由C语言编写,为开发者提供了一站式的算法实现参考。C语言因其高效、灵活和接近硬件的特点,常被用于开发底层算法库。下面我们将...

    计算机专业英语习题.pdf

    - 三种级别的程序设计语言包括:低级语言(直接由计算机执行的机器语言)、汇编语言(接近机器语言的符号语言)、高级语言(更接近人类自然语言的编程语言)。 - 程序设计语言中的共有构造,不同的高级语言之间的...

    MIPS指令集(共31条)

    R型指令是MIPS指令集中最常见的一类,主要用于执行算术和逻辑运算。这类指令的特点是在指令字中包含了用于确定功能的`func`字段。 - **Add** (`add`): 该指令用于对两个寄存器中的值进行加法运算,并将结果存储到第...

    ISO-IEC-13818-1_2000_MPEG2_Systems.pdf

    - **算术运算符 (Arithmetic operators)**:如加号“+”表示加法运算。 - **逻辑运算符 (Logical operators)**:例如,逻辑与“AND”、逻辑或“OR”等。 - **关系运算符 (Relational operators)**:如等于“=”、...

    电路英文缩写.doc

    6. ALU - arithmetic logic unit:算术逻辑单元,是CPU中的核心部件,执行基本的算术和逻辑运算。 7. ASCII - American standard code for information interchange:美国信息交换标准码,一种字符编码标准,用于...

    J2EE面试题

    - 题目12:常见运行时异常包括:`NullPointerException`, `ArrayIndexOutOfBoundsException`, `ArithmeticException`, `ClassCastException`, `IOException`等。 - 题目13:常用接口包括:`Runnable`, `Comparator...

    编程英语词汇汇总.pdf

    在编程领域,掌握相关的英语词汇是至关重要的,因为它构成了编程语言的基础。以下是一些关键的编程英语词汇及其详细解释: 1. JDK(Java Development Kit):Java开发工具包,包含编译、调试和运行Java程序所需的...

    使用IBM静态具优化Java代码.doc

    - 描述:在数学运算中除以0会导致ArithmeticException,是编程中的常见错误。 - 示例:在初始化数组时,若除数为0,将引发异常,但未被捕获(清单2)。 - 解决建议:在进行除法运算前,检查除数是否为0,以避免...

Global site tag (gtag.js) - Google Analytics