Home  >  Article  >  Web Front-end  >  Introduction to operator methods in javascript

Introduction to operator methods in javascript

不言
不言Original
2018-07-16 17:53:141179browse

Operators in js include arithmetic operators and relational operators. Arithmetic operators include unary operators and binary operators. Relational operators include greater than, equal to, less than and identity operators.

Arithmetic operators

Arithmetic operations in JavaScript are mainly implemented through arithmetic operators. Arithmetic operators include unary arithmetic operators and binary arithmetic operators.

Unary arithmetic operators

Unary arithmetic operators are used on a single operand and produce a new value. In JavaScript, unary operators have high priority and are all right-associative

Unary arithmetic operators include unary addition (), unary subtraction (-), increment () and Decrement (--)

Unary addition ( )

The unary addition operator is represented by a plus sign ( ), placed in front of the value, and will not have any impact on the value

var num = 25;
num = +num; //25

When applying the unary plus operator to a non-numeric value, the Number() transformation function will be called to convert the value.

var s1 = '01';
var s2 = '1.1';
var s3 = 'z';
var b = false;
var f = 1.1;
var o = {
    valueOf:function(){
        return -1;
    }
};

s1 = +s1;//1
s2 = +s2;//1.1
s3 = +s3;//NaN
b = +b;//0
f = +f;//1.1
o = +o;//-1

Use the unary plus operator in front of new Date() to convert the date string. It is the number of milliseconds in the date

console.log(new Date());//on Jul 11 2016 20:25:54 GMT+0800 (中国标准时间)
console.log(+new Date());//1468239954076

One-yuan subtraction (-)

The one-yuan subtraction operator is mainly used to represent negative numbers

var num = 25;
num = -num;//-25

When the one-yuan subtraction operator is used for non-numeric values, it will Use the Number() conversion function to convert the value, and then convert the obtained value into a negative number

var s1 = '01';
var s2 = '1.1';
var s3 = 'z';
var b = false;
var f = 1.1;
var o = {
    valueOf:function(){
        return -1;
    }
};

s1 = -s1;//-1
s2 = -s2;//-1.1
s3 = -s3;//NaN
b = -b;//0
f = -f;//-1.1
o = -o;//1
The unary addition and unary subtraction operators are mainly used for basic arithmetic operations and can also be used to convert data types

Increment()

The increment operator increments (adds 1) its operand, which is an lvalue (variable, array element or object attribute). The operator converts the operand into a number through the Number() conversion function, then adds 1 to the number, and reassigns the added value to a variable, numeric element, or object attribute

var age = 29;
++age;
//相当于
var age = 29;
age = age +1;
Return of the increment operator The value depends on its position relative to the operand. When the operator precedes the operand, it is called a pre-increment operator. It performs increment calculation on the operand and returns the calculated value. When the operator is after the operand, it is called a post-increment operator. It performs incremental calculation on the operand but returns an unincremented value.
var i = 1, j = ++i;
//i=2 j=2

var i = 1, j = i++;
//i=2 j=1

Decrement (--)

Decrease--The operand of the operator is also an lvalue. It converts the operand into a number through the Number() conversion function, then subtracts 1, and reassigns the calculated value to Operand

Like the increment operator, the return value of the decrement-operator depends on its position relative to the operand. When the decrement operator is before the operand, the operand is decremented by 1 and returns the value after decrementing 1. value. When the decrement operator is after the operand, the operand is decremented by 1 and the value before decrementing by 1 is returned.

var age = 29;
--age;
//相当于
var age = 29;
age = age - 1;
The precedence of the increment operator is the same as the execution statement, and the entire statement will be evaluated from left to right
var num1 = 2;
var num2 = 20;
var num3 = --num1 + num2;//21
var num4 = num1 + num2;//21
Post-increment operators are executed after the statement containing them is evaluated
var num1 = 2;
var num2 = 20;
var num3 = num1-- + num2;//22
var num4 = num1 + num2;//21

Binary arithmetic operators

Binary arithmetic operators include addition (), subtraction (-), multiplication (*), division (/), and remainder (%)

Addition ( )

In most programming languages, addition is usually a simple numeric operator, However, in ECMAScript, the addition operation has a large number of special behaviors. It can not only perform numerical addition operations, but also perform string concatenation

[1] If one of the operands is an object, the object will be converted to the original value : Date objects perform conversion through the toString() method, and other objects perform conversion through the valueOf() method. Since the valueOf() method of most objects cannot return a primitive value, the conversion will be performed through the toString() method

[Note] In addition to single value arrays that will be converted to numbers, other native objects will use toString() Method to convert to string form

[2] After converting the object to the original value, if one of the operands is a string, the other operand will also be converted to a string, and the string concatenation, otherwise both operands will be converted to numbers or NaN for addition

//单数值数组和valueOf()返回值为数值的自定义对象会转换为数值
console.log(1 + []);//1
var o = {
    valueOf: function(){
        return -1;
    }
}
console.log(1 + o);//0
//其他原生对象则转换为字符串
console.log(1 + {});//'1[object Object]'
console.log(1 + [1,2]);//'11,2'
console.log(1 + new Date());//'1Thu Jun 16 2016 10:27:13 GMT+0800 (中国标准时间)'
console.log(1 + /0/);//'1/0/'

If doing arithmetic addition, undefined is converted to NaN, null is converted to 0, false is converted to 0, and true is converted to 1

console.log('' + undefined);//'undefined'
console.log('' + null);//'null'
console.log('' + false);//'false'
console.log('' + true);//'true'

Therefore, using the characteristics of the plus operator, you can use '' to convert any type value into a string

Subtraction (-)

Compared to addition, subtraction It's much simpler and only involves the subtraction of numbers. Use the Number() conversion function to convert non-numeric types to numeric values ​​or NaN

console.log(1 - {});//NaN
console.log(1 - [1,2]);//NaN
console.log(1 - /0/);//NaN
console.log(1 - []);//1
A special feature of addition is that when the time Date object is added, toString() is used to convert it to a string, while in other mathematics In operations, including subtraction, multiplication, division, remainder, etc., the Number() conversion function is used to convert the time Date object into a number using valueOf()
console.log(new Date() + 1);//'Thu Jun 16 2016 11:11:49 GMT+0800 (中国标准时间)1'
console.log(new Date() - 1);//1466046941641

undefined is converted to NaN, and null is converted to 0 , false is converted to 0, true is converted to 1

console.log(1 - undefined);//NaN
console.log(1 - null);//1
console.log(1 - false);//1
console.log(1 - true);//0

Multiplication (*)

The multiplication operator is represented by an asterisk (*) and is used to calculate the product of two values. It will be passed Number() conversion function converts non-numeric types to numeric values ​​or NaN

+ Infinity * 0;//NaN
- Infinity * 0;//NaN
Infinity * 非0数值;//Infinity或-Infinity
Infinity * Infinity;//Infinity

Division (/)

The division operator is represented by a slash (/) and performs division of the first operand With the operation of the second operand, the non-numeric type will also be converted to a numeric value or NaN

through the Number() conversion function.
Infinity / Infinity;//NaN
0 / 0;//NaN
非0数值 / 0;//Infinity或-Infinity
Infinity / 0;//Infinity
Infinity / 非0数值;//Infinity

求模(%)

求模(余数)操作符是由一个百分号(%)表示,是第一个操作数除以第二个操作数的余数

//r是余数,n是被除数,d是除数,
//q是整数,在n/d为负时为负,在n/d为正时为正,它应该在不超过n和d的商的前提下尽可能大
r = n - (d * q)

求模结果与第一个操作数的符号保持一致

console.log(5 % 2);//1
console.log(5 % -2);//1
console.log(-5 % 2);//-1
console.log(-5 % -2);//-1

关系运算符

关系运算符用于测试两个值之间的关系,根据关系是否存在而返回true或false,关系表达式总是返回一个布尔值,通常在if、while或for语句中使用关系表达式,用以控制程序的执行流程

javascript提供了===、!==、==、!=、<、<=、>、>=8个关系运算符,分为4类介绍关系运算符

恒等运算符

恒等运算符'===',也叫严格相等运算符,首先计算其操作数的值,然后比较这两个值,比较过程没有任何类型转换,比较过程如下:

【1】如果两个值的类型不相同,则返回false

console.log(1 === '1');//false
console.log(1 === [1]);//false

【2】如果两个值都是Undefined、Null、Boolean、Number、String相同原始类型的值,值相同,就返回true,否则,返回false

console.log(undefined === undefined);//true
console.log(null === null);//true
console.log(true === true);//true
console.log(false === false);//true
console.log(1 === 1);//true
console.log(2.5 === 2.5);//true

[注意]不论什么进制的数字,在进行关系比较时,最终都转换为十进制进行运算

console.log(10 === 0xa);//true

在数字Number类型中,有一个值比较特殊,是NaN(not a number),它与任何值都不相等;此外,数字Number类型中存在着+0和-0,虽然其符号不同,但值相等

console.log(NaN === NaN);//false
console.log(+0 === -0);//true

两个相同字符串值表现为:相同的长度和相同的字符对应相同的位置

console.log('abc' === 'abc');//true
console.log('abc' === 'acb');//false

【3】如果两个值引用同一个对象,则返回true,否则,返回false

[注意]更详细的解释是,javascript对象的比较是引用的比较,而不是值的比较。对象和其本身是相等的,但和其他任何对象都不相等。如果两个不同的对象具有相同数量的属性,相同的属性名和值,它们依然是不相等的

console.log([] === []);//false
console.log({} === {});//false    
console.log(function(){} === function(){});//false
var a = {};
b = a;
console.log(a === b);//true

恒不等运算符(!==)又叫严格不等于运算符,操作数的比较过程与恒等运算符相同,结果取反。如果'==='的比较结果是true,则'!=='的比较结果是false;如果'==='的比较结果是false,则'!=='的比较结果是true

console.log(1 !== '1');//true
console.log(1 !== 1);//false
console.log(true !== false);//true
console.log({} !== {});//true

相等运算符

相等运算符'=='和恒等运算符相似,但相等运算符的比较并不严格,如果两个操作数不是同一类型,相等运算符会尝试进行一些类型转换,然后再进行比较

当两个操作数类型相同时,比较规则和恒等运算符规则相同

console.log(undefined == undefined);//true
console.log(10 == 0xa);//true
console.log(NaN == NaN);//false
console.log([] == []);//false

当两个操作数类型不同时,相等运算符'=='会遵守如下规则:

【1】如果一个值是对象类型,另一值是原始类型,则对象类型会先使用valueOf()转换成原始值,如果结果还不是原始值,则再使用toString()方法转换,再进行比较

[注意]日期类只允许使用toString()方法转换为字符串。类似地,时间Date对象进行加法运算时使用toString()转换为字符串,而在其他数学运算,包括减法、乘法、除法、求余等运算中,都是使用Number()转换函数将时间Date对象使用valueOf()转换为数字

【2】在对象转换为原始值之后,如果两个操作数都是字符串,则进行字符串的比较

console.log(new Date() == 'Sat Jun 25 2016 11:07:20 GMT+0800 (中国标准时间)');//true

【3】在对象转换为原始值之后,如果至少有一个操作数不是字符串,则两个操作数都将通过Number()转型函数转换成数字进行数值比较

console.log(true == 1);//true
console.log(true == 0);//false
console.log(false == '1');//false
console.log(false == '0');//true
console.log(true == 'true');//false,相当于1 == NaN

console.log([1] == 1);//true,相当于1 == 1
console.log([1] == '1');//true,相当于'1' == '1'
console.log([] == 0);//true,相当于0 == 0
console.log([] == '0');//false,相当于'' == '0'

console.log([] == true);//false,相当于0 == 1
console.log([1] == true);//true,相当于1 == 1
var a = {
    valueOf:function(){
        return 1;
    },
    toString:function(){
        return '2';
    }
} 
console.log( a == '1');//true,相当于1 == 1

var a = {
    valueOf:function(){
        return {};
    },
    toString:function(){
        return '1';
    }
} 
console.log( a == 1);//true,相当于1 == 1

[注意]如果一个值是null,另一个值是undefined,则返回true。虽然Number(null)是0,但null和0并不相等

console.log(null == undefined);//true
console.log(null == 0);//false

[注意]空字符串或空格字符串会转成0

console.log(null == []);//false
console.log(null == '');//false
console.log([] == ' ');//false,相当于'' == ' '
console.log([] == '');//true,相当于'' == ''
console.log(0 == '');//true

不相等运算符(!=)的操作数比较过程与相等运算符相同,结果取反。如果'=='的比较结果是true,则'!='的比较结果是false;如果'=='的比较结果是false,则'!='的比较结果是true

console.log(1 != '1');//false,相当于1 != 1
console.log(true != '1');//false,相当于1 != 1
console.log('true' != 1);//true,相当于NaN != 1
console.log([1] != '1');//false,相当于'1' != '1'
console.log([1] != true);//false,相当于1 != 1

大于运算符

大于运算符(>)用于比较两个操作数,如果第一个操作数大于第二个操作数,则大于运算符的计算结果为true,否则为false

大于运算符的操作数可能是任意类型,然而,只有数字和字符串才能真正执行比较操作,因此那些不是数字和字符串的操作数都将进行类型转换,类型转换规则如下:

【1】如果操作数是对象,则这个对象将先使用valueOf()转换成原始值,如果结果还不是原始值,则再使用toString()方法转换

[注意]实际上,在原生对象中,使用valueOf()方法转换为原始值的,只有转换为数字Number类型的时间Date对象,其他对象都通过toString()方法转换为字符串

【2】在对象转换为原始值之后,如果两个操作数都是字符串,则按照字母表的顺序对两个字符串进行比较,这里提到的字母表顺序是指组成这个字符串的16位unicode字符的索引顺序

console.log('b' > 'a');//true
console.log('B' > 'a');//false

console.log({} > '[a]');//true,相当于'[object Object]' > '[a]'
console.log({} > '[p]');//false,相当于'[object Object]' > '[p]'

console.log(['a'] > ['b']);//false,相当于'a' > 'b'
console.log([2] > [11]);//true,相当于'2' > '11'

【3】在对象转换为原始值之后,如果至少有一个操作数不是字符串,则两个操作数都转换成数字进行比较

[注意]在等于操作符中,时间Date()对象只允许通过toString()方法转换为字符串,而不允许通过valueOf()方法转换为数字;而在大于操作符中,时间Date()对象允许优先使用valueOf()方法转换为数字

console.log(new Date() > 100);//true,相当于1466826928667 > 100
console.log(true > [0]);//true,相当于 1 > 0

console.log(2 > 1);//true
console.log(11 > '2');//true,相当于11 > 2

console.log(NaN > 1);//false
console.log(1 > NaN);//false
console.log({} > true);//false,相当于 NaN > 1

对于数字和字符串来说,加号运算符和比较运算符的行为有所不同,加号运算符更偏爱字符串,如果它的一个操作数是字符串,就进行字符串连接。而比较运算符则更偏爱数字,只有在两个操作数都是字符串时,才进行字符串的比较

console.log(1 + 2);//3
console.log('1' + '2');//'12'
console.log('1' + 2);//'12',相当于 '1' + '2'

console.log(2 > 1);//true
console.log('2' > '1');//true
console.log('2' > 1);//true,相当于 2 > 1

小于等于运算符(<=)并不依赖于小于或等于运算符的比较规则,而是遵循大于运算符的比较规则,结果取反。如果'>'的比较结果是true,则'<='的比较结果是false;如果'>'的比较结果是false,则'<='的比较结果是true

console.log(1 <= &#39;0&#39;);//false,相当于1 <= 0
console.log(true <= &#39;0&#39;);//false,相当于1 <= 0
console.log(&#39;true&#39; <= 0);//false,相当于NaN <= 0
console.log([1] <= &#39;0&#39;);//false,相当于&#39;1&#39; <= &#39;0&#39;
console.log([0] <= true);//true,相当于0 <= 1
console.log(1 <= 1);//true

小于运算符

小于运算符(<)用于比较两个操作数,如果第一个操作数小于第二个操作数,则小于运算符的计算结果为true,否则为false

小于运算符与大于运算符的类型转换规则类似,就不再赘述

同样地,大于等于运算符(>=)并不依赖于大于或等于运算符的比较规则,而是遵循小于运算符的比较规则,结果取反。如果'<'的比较结果是true,则'>='的结果是false;如果'<'的比较结果是false,则'>='的结果是true

相关推荐:

js与运算符和或运算符的妙用_javascript技巧

JS的递增/递减运算符和带操作的赋值运算符的等价式_javascript技巧

The above is the detailed content of Introduction to operator methods in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn