javascript运算符_JavaScript一元运算符:简单而有用

javascript运算符

You might have come across things like i++, --i in loops or ** !** when writing conditions. Ever wondered how these operations work? Well, these are unary operators and we are going to take an in-depth look into how they work.

你可能会在循环或**!**书写时的条件所遇到的事情就像++,--i。 有没有想过这些操作如何工作? 好吧,这些都是一元运算符,我们将深入研究它们的工作方式。

什么是运算符? ( What is an operator? )

javascript运算符_JavaScript一元运算符:简单而有用_第1张图片 Mathematically, an
operation is a calculation on one or more values called operands mapping to an output value. An operator is a symbol/sign that maps operands to output values.

运算是对一个或多个称为操作数的值映射到输出值的计算。 运算符是将操作数映射到输出值的符号/符号。

什么是一元运算符? ( What is an unary operator? )

A unary operator is one that takes a single operand/argument and performs an operation.

一元运算符是采用单个操作数/参数并执行一个运算的运算符。

A unary operation is an operation with only one operand. This operand comes either before or after the operator. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.

一元运算是只有一个操作数的运算。 该操作数位于运算符之前或之后。 一元运算符比标准JavaScript函数调用更有效。 此外,一元运算符不能被覆盖,因此可以保证其功能。

所有一元运算符的摘要 ( Summary of all unary operators )

Operator Explanation
Unary plus (+) Tries to convert the operand into a number
*Unary negation (-) * Tries to convert the operand into a number and negates after
Logical Not (!) Converts to boolean value then negates it
Increment (++) Adds one to its operand
Decrement (--) Decrements by one from its operand
Bitwise not (~) Inverts all the bits in the operand and returns a number
typeof Returns a string which is the type of the operand
delete Deletes specific index of an array or specific property of an object
void Discards a return value of an expression.
操作员 说明
一元加(+) 尝试将操作数转换为数字
* 一元否定(-)* 尝试将操作数转换为数字,然后取反
逻辑不(!) 转换为布尔值然后取反
增量(++) 向其操作数加一
减量(-) 从其操作数减一
按位不(〜) 反转操作数中的所有位并返回一个数字
类型 返回一个字符串,它是操作数的类型
删除 删除数组的特定索引或对象的特定属性
虚空 丢弃表达式的返回值。

一元加(+) ( Unary plus (+) )

This operator precedes the operand and tries to convert it to a number.

该运算符位于操作数之前,并尝试将其转换为数字。

It can convert all string representations of numbers, boolean values(true and false) and null to numbers. Numbers will include both integers, floats, hexadecimal, scientific (exponent) notation and Infinity.

它可以将数字,布尔值(真和假)和null的所有字符串表示形式转换为数字。 数字将包括整数,浮点数,十六进制,科学(指数)表示法和无穷大。

If the operand cannot be converted into a number, the unary plus operator will return NaN.

如果操作数不能转换为数字,则一元加运算符将返回NaN

Examples:

例子:

+3                                   // returns 3
    +'-3'                                // returns -3
    +'3.14'                              // returns 3.14
    +'3'                                 // returns 3
    +'0xFF'                              // returns 255
    +true                                // returns 1
    +'123e-5'                            // returns 0.00123
    +false                               // returns 0
    +null                                // returns 0
    +'Infinity'                          // returns Infinity
    +'infinity'                          // returns NaN
    +function(val){
         return val }        // returns NaN

The illustration above clearly shows how the + operator will behave when applied to different data types.

上面的插图清楚地显示了+运算符应用于不同数据类型时的行为。

  • Numbers will not be altered.

    数字不会改变。
  • A string notation of a number e.g '3' is converted to that number (3).

    数字(例如“ 3” )的字符串表示法将转换为该数字( 3 )。
  • Boolean value true is converted to a 1 and false to 0.

    布尔值true转换为1, false转换为0。
  • Other types e.g functions and objects are converted to NaN.

    其他类型(例如,函数和对象)将转换为NaN。

Note

注意

An object can only be converted if it has a key valueOf and it's function returns any of the above types.

仅当对象具有键valueOf并且其函数返回上述任何一种类型时,才可以转换该对象。

+{
       
  valueOf: function(){
       
    return '0xFF'
  }
}
//returns 255

一元否定(-) ( Unary negation (-) )

It also precedes the operand and converts non-numbers data types to numbers like unary plus, however, it performs an additional operation, negation.

它也位于操作数之前,并将非数字数据类型转换为一元加号之类的数字,但是,它执行附加运算,取反。

Unary plus is considered the fastest and preferred way of making conversions because it doesn't perform any additional operation. Both the unary negation and plus perform the same operation as the Number() function for non-numbers.

一元加号被认为是进行转化的最快,首选的方式,因为它不执行任何其他操作。 一元否定和加号都与非数字的Number()函数执行相同的操作。

Examples:

例子:

-3                               // returns -3
    -'-3'                            // returns 3
    -'3.14'                          // returns -3.14
    -'3'                             // returns -3
    -'0xFF'                          // returns -255
    -true                            // returns -1
    -'123e-5'                        // returns -0.00123
    -false                           // returns -0
    -null                            // returns -0
    -'Infinity'                      // returns -Infinity
    -'infinity'                      // returns NaN
    -function(val){
         return val }    // returns NaN
  -{
            valueOf: function(){
       
      return '0xFF'
    }
  }                                //returns -255

逻辑不(!) ( Logical Not (!) )

This operator comes before the operand. It converts the operand into it's boolean equivalent before negating it.

该运算符位于操作数之前。 求反之前,它将操作数转换为等效的布尔值。

Examples:

例子:

!false        // returns true
!NaN          // returns true
!0            // returns true
!null         // returns true
!undefined    // returns true
!""           // returns true
!true         // returns false
!-3           // returns false
!"-3"         // returns false
!42           // returns false
!"42"         // returns false
!"foo"        // returns false
!"true"       // returns false
!"false"      // returns false
!{
       }           // returns false
![]           // returns false
!function(){
       } // returns false

The above illustration demonstrates how logical not returns ** false** if the operand can be converted to true, if not it returns false.

上图说明了如果操作数可以转换为true,则逻辑不返回** false **的方式;否则,逻辑不返回false。

You can use double negation(!!)

您可以使用双重否定(!!)

Let us take a look at a more awesome example:

让我们看一个更棒的示例:

!!'hi' === true  // returns true
!!1 === true    // returns true
!!0 === false  // returns true

Why true? So we execute from right to left.

为何如此? 因此,我们从右到左执行。

!'hi'  //returns false

Then:

然后:

!false //returns true

Thus:

从而:

true === true //returns true

增量(++) ( Increment (++) )

This operator adds one to its operand and returns the result.

该运算符在其操作数上加一个并返回结果。

It can be used as a postfix or prefix operator.

它可以用作后缀或前缀运算符。

  • Postfix : - meaning the operator comes after the operand(y++). This returns the value before incrementing.

    后缀:-表示运算符在操作数(y ++)之后。 这将返回递增之前的值。
  • Prefix: - the operator comes before the operand (++y). Using it as a prefix, returns the value after incrementing.

    前缀:-运算符位于操作数(++ y)之前。 将其用作前缀,递增后返回值。

Examples:

例子:

Postfix

后缀

x= 4      // x=4
y = x++    // y = 4 and  x = 5
// y is set to the value before incrementing and it adds 1 to x

// Be careful about resetting values when using postfix
var a = 5     // a = 5
a = a++       // a = 5
// a is set to the value before incrementing

Prefix

字首

x= 4      // x=4
y = ++x    // y = 5 and  x = 5
// y is set to the value after incrementing and it adds 1 to x

var a = 5     // a = 5
a = ++a       // a = 6
// a is set to the value after incrementing

减量(-) ( Decrement (--) )

The decrement operator subtracts one from its operand.

减量运算符从其操作数中减去1。

It returns a value before decrementing if it is postfix. Prefixing it returns the value after decrementing.

如果它是后缀,它将在递减之前返回一个值。 前缀后,递减后将返回值。

Examples:

例子:

Postfix

后缀

var a = 5     // a = 5
a = a--       // a = 5
// a is set to the value before incrementing

x = 4      // x=4
y = x--    // y = 4 and  x = 3
// sets y to the value before decrementing and it removes 1 from x

Prefix

字首

var a = 5  // a = 5
a = --a    // a = 4
// a is set to the value after incrementing

x = 4      // x=4
y = --x    // y =3 and  x = 3
// sets y to the value after incrementing and it adds 1 to x

按位不(〜) ( Bitwise not (~) )

Performs a binary NOT operation, by inverting all the bits in the operand and return a number.

通过反转操作数中的所有位并返回一个数字来执行二进制NOT运算。

A bitwise not on a number results in: -(x + 1).

按位不在数字上的结果是-(x + 1)

a Not a
0 1
1 0
一个 不是
0 1个
1个 0

Examples:

例子:

~2                                  //returns -3
~'2'                                //returns -3
~'-3'                               // returns 2
-'-3.14'                            // returns 2
~'-3.54'                            // returns 2
~'0xFF'                             // returns -256
~true                               // returns -2
~'123e-5'                           // returns -1
~false                              // returns -1
~null                               // returns -1
~'Infinity'                         // returns -1
~'infinity'                         // returns -1
~function(val){
         return val }       // returns -1
~{
            valueOf: function(){
       
        return '0xFF'
    }
}                                  //returns -256

The table below takes a deeper look into how this operation is performed.

下表更深入地介绍了此操作的执行方式。

(base 10) (base 2) Not (base 2) Not (base 10)
2 00000010 11111101 -3
1 00000001 11111110 -2
0 00000000 11111111 -1
-1 11111111 00000000 0
-2 11111110 00000001 1
-3 11111101 00000010 2
(以10为基数) (基数2) 不(以2为底) 不(以10为基数)
2 00000010 11111101 -3
1个 00000001 11111110 -2
0 00000000 11111111 -1
-1 11111111 00000000 0
-2 11111110 00000001 1个
-3 11111101 00000010 2

类型 ( typeof )

This operator comes before the operand. It returns a string indicating the data type of the operand.

该运算符位于操作数之前。 它返回一个字符串,指示操作数的数据类型。

Examples:

例子:

typeof 2                                       // returns 'number'
typeof -3.14                                   // returns 'number'
typeof 0xFF                                    // returns 'number'
typeof 123e-5                                  // returns 'number'
typeof true                                    // returns 'boolean'
typeof false                                   // returns 'boolean'
typeof null                                    // returns 'object'
typeof Infinity                                // returns 'number'
typeof '2'                                     // returns 'string'
typeof '-3'                                    // returns 'string'
typeof 'infinity'                              // returns 'string'
typeof Date()                                  // returns 'string'
typeof [1,2,3]                                 // returns 'object'
typeof {
       hi: 'world'}                           // returns 'object'
typeof function(val){
         return val }            // returns 'function'
typeof {
            valueOf: function(){
       
        return '0xFF'
    }
}                                              // returns 'object'
typeof undefined                               // returns 'undefined'
typeof hi                                      // returns 'undefined'
typeof NaN                                     // returns 'number'
typeof new Date()                              // returns 'object'
typeof /ab+c/                                  // returns 'object'
typeof new RegExp('ab+c')                      // returns 'object'
typeof document                                // returns 'undefined'

删除: ( delete: )

It also comes before the operand. It deletes values of a specific index of an array and a specific property of an object.

它也位于操作数之前。 它删除数组的特定索引和对象的特定属性的值。

It returns true if it successfully deleted the property or if the property does not exist. It returns** false** if it fails to delete an item.

如果成功删除了该属性或该属性不存在,则返回true 。 如果未能删除项目,则返回** false **。

Delete does not have any effect on both functions and variables. Let's look at the following examples.

删除对函数和变量都没有任何影响。 让我们看下面的例子

// Deleting a variable
var hi = 1;
delete hi;          // returns false
console.log(hi);    // returns 1

// Deleting a function
function yo(){
        };
delete yo;           // returns false
console.log(yo);     // returns function foo(){ }

// Deleting an object
var pub = {
       bar: '1'}
delete pub           // returns false
console.log(pub);    // returns {bar: '1'}

//Deleting an array
var code = [1,1,2,3,5]
delete code          // returns false
console.log(code);   //  [1,1,2,3,5]

Objects

对象

As earlier stated, it deletes the property or the whole object. Examples:

如前所述,它将删除属性或整个对象。 例子:

// Deleting a property with the literal notation
var fruits = {
       1: 'apple', 2: 'mango'}
delete fruits[1]             // returns true
console.log(fruits);         // returns { '2': 'mango' }
console.log(fruits[1]);      // returns undefined

// Deleting a property with the dot notation
var pub = {
        bar: "42" };
delete pub.bar;              // returns true
console.log(pub);            // returns {}

// Deleting a property that does not exist
var lunch = {
        fries: 1 };
delete lunch.beans;          // returns true
console.log(lunch);          // returns { fries: 1 }

// Deleting a non-configurable property of a predefined object
delete Math.PI;              // returns false console.log(Math.PI);        // returns 3.141592653589793

Non-Configurable properties

不可配置的属性

Delete has no effect on an object property that is as non-configurable. It will always return false. In strict mode, this will raise a SyntaxError.

删除对不可配置的对象属性没有影响。 它将始终返回false。 在严格模式下,这将引发SyntaxError。

Examples:

例子:

// When Non Configurable
var Person = {
       };
Object.defineProperty(Person, 'name', {
         value: 'Scot', configurable: false })
// Defines an object property and sets it to non-configurable
console.log(Person.value);                                    // returns 'Scot'
delete Person.value                                           // returns false
console.log(Person.value);                                    // returns 'Scot'

// When configurable
var b = {
       };
Object.defineProperty(Person, 'name', {
         value: 'Scot', configurable: true })
console.log(b.value);                                    // returns 'Scot'
delete b.value                                           // returns true
console.log(b.value);                                    // returns undefined

Read more about defineProperty()

阅读有关defineProperty()的更多信息

var, let and const create non-configurable properties that cannot be deleted with the delete operator:

var,let和const创建不可配置的属性 ,这些属性无法使用delete运算符删除:

Example:

例:

var num = 1;
// We can access this global property using:
Object.getOwnPropertyDescriptor(window, 'num') // returns { value: 'XYZ',
//           writable: true,
//           enumerable: true,
//           configurable: false } delete num;                                     // returns false
// Node
Object.getOwnPropertyDescriptor(global, 'num')
// returns { value: 'XYZ',
//           writable: true,
//           enumerable: true,
//           configurable: false }
// regular objects
var lunch = {
        fries: 1 }; Object.getOwnPropertyDescriptor(lunch, 'fries')
// returns { value: 1,
//           writable: true,
//           enumerable: true,
//           configurable: true }

Notice that the var keyword is marked as non-configurable

请注意,var关键字被标记为不可配置

Arrays

数组

Arrays are considered type object in javascript. Thus this method will work on them.

数组在javascript中被视为类型对象 。 因此,该方法将对它们起作用。

Examples:

例子:

// Deleting values of an array index
var lol=[20,30,40];
console.log(lol.length);     // returns 3
delete lol[2]                // returns true
console.log(lol);            // returns [ 20, 30,  ]
console.log(lol[2]);         // returns undefined
console.log(lol.length);     // returns 3

Note

注意

The delete operator will only delete the value and *not the index *of the array. It will leave the value of that particular index as undefined. This is why the length does not change.

delete运算符将只删除值,而不是数组的索引 。 它将使该特定索引的值保持未定义状态。 这就是长度不变的原因。

strict mode

严格模式

In strict mode, delete throws a SyntaxError due to the use of direct reference to a variable, a function argument or a function name.

在严格模式下,由于直接引用变量,函数参数或函数名称,因此delete引发SyntaxError。

‘use strict’var fruits = {
       1:'mango', 2:'apple'};
delete fruits;
// Output: Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

function Person() {
       
 delete name;             // SyntaxError
 var name; }

function yo() {
       
}

delete yo; // SyntaxError

Here are a few pointers to always consider when using delete:

以下是使用delete时要始终考虑的一些提示:

  • Trying to delete a property that does not exist, delete will return true but will not have an effect on the object.

    尝试删除不存在的属性时,delete将返回true,但不会对该对象产生影响。

  • Delete only affects object own properties. This means if a property with the same name exists on the object's prototype chain, then delete will not affect it. After deletion, the object will use the property from the prototype chain.

    删除仅影响对象自己的属性。 这意味着,如果对象的原型链上存在具有相同名称的属性,则删除不会影响它。 删除后,对象将使用原型链中的属性。

  • Variable declared var,_ let_ and const cannot be deleted from the global scope or from a function's scope.

    • Meaning:- Delete cannot delete any functions in the global scope or in the function scope.
    • Delete works on functions which are part of an object (apart from the global scope).

    声明为var ,_ let_和const的变量不能从全局范围或函数范围中删除。

    • 含义:- 删除不能删除全局范围或功能范围中的任何功能。
    • Delete对属于对象一部分的函数起作用(除了全局作用域之外)。
  • Non-configurable properties cannot be removed.

    不可配置的属性无法删除。

  • Delete does not work on any of the built-in objects like Math, Array, Object or properties that are created as non-configurable with methods like Object.defineProperty().

    删除不适用于任何内置对象(例如Math,Array,Object)或使用Object.defineProperty()等方法创建为不可配置的属性。

无效运算符: ( Void operator: )

It precedes an operation. It discards the return value of an expression, meaning it evaluates an expression but returns undefined.

它在操作之前。 它丢弃表达式的返回值,这意味着它对一个表达式求值但未定义。

Void operator's main purpose is to return undefined. The void operator specifies an expression to be evaluated without returning a value.

无效运算符的主要目的是返回未定义的值。 void运算符指定要求值的表达式,但不返回值。

The void operator is used in either of the following ways: void (expression) void expression

可以通过以下两种方式之一使用void运算符: void(expression) void expression

Note:

注意:

The void operator is not a function, so () are not required, but it is good style to use them according to MDN

void运算符不是函数,因此()不是必需的,但是根据MDN使用它们是一种很好的样式

Example:

例:

void 0                                              // returns undefined
var hi = function () {
       
    console.log('Yap')
    return 4;
}
var result = hi()                                   // logs 'Yap' and returns 4
console.log(result);                                // returns 4

var voidResult = void (hi())                        // logs 'Yap' and returns undefined
console.log(voidResult);                             // returns undefined

The void operator can be used to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

void运算符可用于将表达式指定为超文本链接。 该表达式已求值,但未代替当前文档加载。

Some more examples

更多例子

<a href="javascript:void(0)">Click here to do nothinga>

The code above creates a link that does nothing when a user clicks it. This is because void(0) evaluates to undefined.

上面的代码创建了一个链接,当用户单击该链接时,该链接不执行任何操作。 这是因为void(0)的值为undefined。

<a href="javascript:void(document.form.submit())">
Click here to submita>

The code creates a link that submits a form when the user clicks it.

该代码创建一个链接,当用户单击该链接时将提交一个表单。

结论 ( Conclusion )

Always consider the order of operations when dealing with more than one operator. This is good practice in mitigating unforeseen bugs.

与多个操作员打交道时,请务必考虑操作顺序。 这是缓解无法预料的错误的好习惯。

Here is a brief table that shows the order of precedence in operations when using Javascript. Operands on the same level have the same order of precedence.

这是一个简短的表格,显示了使用Javascript时操作的优先顺序。 同一级别上的操作数具有相同的优先级顺序。

Operator type Operators Example
member . [] [1,2,3]
call / create instance () new var vehicle = new Vehicle();
negation/increment ! ~ - + ++ -- typeof void delete typeof [1,2,2]
multiply/divide * / % 3 % 3
addition/subtraction + - 3 + 3
bitwise shift << >> >>> 9 << 2
relational < <= > >= in instanceof [1] instanceof Array
*equality * == != === !== void(0) === undefined
bitwise-and & 5 & 1
*bitwise-xor * ^ 5 ^ 1
bitwise-or \
logical-and && x < 10 && y > 1
logical-or \ \
conditional ?: (age < 18) ? "Too young":"Old enough"
assignment = += -= *= /= %= <<= >>= >>>= &= ^= \ =
*comma * , b = 3, c = 4
操作员类型 经营者
会员 。 [] [1,2,3]
调用/创建实例 ()新 var vehicle = new Vehicle();
求反/增量 ! 〜-+ ++-typeof void删除 typeof [1,2,2]
乘/除 * /% 3%3
加/减 +- 3 + 3
按位移位 << >> >>> 9 << 2
关系的 <<=>> = in instanceof [1]数组实例
* 平等* ==!= ===!== void(0)===未定义
按位与 5和1
* 按位异或* ^ 5 ^ 1
按位或 \
逻辑与 && x <10 && y> 1
逻辑或 \ \
有条件的 ?: (年龄<18岁)? “太年轻”:“够老了”
分配 = + =-= * = / =%= << = >> = >>> =&= ^ = \ =
* 逗号* b = 3,c = 4

翻译自: https://scotch.io/tutorials/javascript-unary-operators-simple-and-useful

javascript运算符

你可能感兴趣的:(javascript,java,js,python,vue)