Home > Web Front-end > JS Tutorial > Introduction to operators and expressions in JavaScript

Introduction to operators and expressions in JavaScript

不言
Release: 2018-09-11 17:01:33
Original
1459 people have browsed it

This article brings you an introduction to operators and expressions in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Unary operator

1.delete operator

The delete operator is used to delete an attribute of an object; if there is no reference to this attribute, then it It will eventually be released

Syntax: delete expression

The delete operator will remove the specified attribute from an object. Returns true when deleted successfully, otherwise returns false

   let Employee = {
        age: 28,
        name: 'abc',
        designation: 'developer'
    };
    console.log(delete Employee.name);   // returns true
    console.log(delete Employee.age);    // returns true
    console.log(Employee); //{designation: "developer"}
Copy after login

2.typeof operator

The typeof operator returns a string indicating the type of the uncalculated operand

Syntax: typeof operand; typeof (operand);

    typeof NaN === 'number';
    typeof Number(1) === 'number';
    typeof "" === 'string';
    typeof true === 'boolean';
    typeof Symbol('foo') === 'symbol';
    typeof undefined === 'undefined';
    typeof null === 'object'
    typeof [1, 2, 4] === 'object';
    typeof new Boolean(true) === 'object';
    typeof new Number(1) === 'object';
    typeof new String("abc") === 'object';
    typeof function(){} === 'function';
Copy after login

3.void operator

The void operator evaluates the given expression and returns undefined

Syntax: void expression

<a href="javascript:void(0);">
  这个链接点击之后不会做任何事情,如果去掉 void(),
  点击之后整个页面会被替换成一个字符 0。
</a>
<p> chrome中即使<a href="javascript:0;">也没变化,firefox中会变成一个字符串0 </p>
<a href="javascript:void(document.body.style.backgroundColor=&#39;green&#39;);">
  点击这个链接会让页面背景变成绿色。
</a>
Copy after login

2. Relational operators

1.in operator

If the specified attribute is in the specified object or its prototype chain, then in operator returns true

Syntax: prop in object

    let trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    console.log(0 in trees); // 返回true
    console.log(3 in trees); // 返回true
    console.log(6 in trees); // 返回false
    console.log("bay" in trees); // 返回false (必须使用索引号,而不是数组元素的值)
    console.log("length" in trees); // 返回true (length是一个数组属性)
Copy after login

2.instanceof operator

instanceof operator is used to test whether an object exists in its prototype chain The prototype attribute of the constructor

Syntax: object instanceof constructor

    let simpleStr = "This is a simple string";
    let myString  = new String();
    let newStr    = new String("String created with constructor");
    let myDate    = new Date();
    let myObj     = {};
    simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefined
    myString  instanceof String; // 返回 true
    newStr    instanceof String; // 返回 true
    myString  instanceof Object; // 返回 true
    myDate instanceof Date;     // 返回 true
    myObj instanceof Object;    // 返回 true, 尽管原型没有定义
Copy after login

3. Expression

1.this

Inside the function, the value of this depends on to the way the function is called. In strict mode, this will retain the value it had when it entered the execution context, so the following this will default to undefined

function f2(){
  "use strict"; // 这里是严格模式
  return this;
}
f2() === undefined; // true
Copy after login

When a function uses the this keyword in its body, it can be inherited by using function Bind this value to the specific object in the call from the call or apply method of Function.prototype

function add(c, d) {
  return this.a + this.b + c + d;
}
let o = {a: 1, b: 3};
// 第一个参数是作为‘this’使用的对象
// 后续参数作为参数传递给函数调用
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
Copy after login

Calling f.bind(someObject) will create a function with the same function body and scope as f, but In this new function, this will be permanently bound to the first parameter of bind, no matter how this function is called

function f(){
  return this.a;
}
let g = f.bind({a:"azerty"});
console.log(g()); // azerty
let h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty
Copy after login

In arrow functions, this is consistent with the this of the enclosing lexical context . In the global code, it will be set to the global object

let globalObject = this;
let foo = (() => this);
console.log(foo() === globalObject); // true
Copy after login

2.super

Syntax:
super([arguments]); // Call the constructor of the parent object/parent class Function
super.functionOnParent([arguments]); // Call the method on the parent object/parent class

When used in the constructor, the super keyword will appear alone and must be used with the this key used before the word. The super keyword can also be used to call functions on the parent object

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  }
}
Computer.pingpong(); // 'ping pong'
Copy after login

3.new

new operator creates an instance of a user-defined object type or an instance of a built-in object with a constructor

function Car() {}
car1 = new Car()
console.log(car1.color)           // undefined
Car.prototype.color = null
console.log(car1.color)           // null
car1.color = "black"
console.log(car1.color)           // black
Copy after login

4. Expansion syntax

You can expand array expressions or strings at the syntax level during function calls/array construction; you can also expand object expressions when constructing literal objects Expand in a key-value manner

Use expansion syntax when calling a function

function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction.apply(null, args);

//展开语法
function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction(...args);
Copy after login

Use expansion syntax when constructing a literal array

let parts = ['shoulders','knees']; 
let lyrics = ['head',... parts,'and','toes']; 
// ["head", "shoulders", "knees", "and", "toes"]
Copy after login

Array copy

let arr = [1, 2, 3];
let arr2 = [...arr]; // like arr.slice()
arr2.push(4); 

// arr2 此时变成 [1, 2, 3, 4]
// arr 不受影响
Copy after login

Connect multiple arrays

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
// 将 arr2 中所有元素附加到 arr1 后面并返回
let arr3 = arr1.concat(arr2);

//使用展开语法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
let arr3 = [...arr1, ...arr2];
Copy after login

5. Class expression

Class expression It is a syntax used to define classes

let Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};
let instance = new Foo();
instance.bar(); 
// "Hello World!"
Copy after login

6. Function expression

The function keyword can be used to define a function in an expression. You can also use the Function constructor and A function declaration to define a function
Function declaration hoisting and function expression hoisting: Function expressions in JavaScript are not hoisted, unlike function declarations, you cannot use function expressions before defining them

/* 函数声明 */

foo(); // "bar"
function foo() {
  console.log("bar");
}


/* 函数表达式 */

baz(); // TypeError: baz is not a function
let baz = function() {
  console.log("bar2");
};
Copy after login

7.function*Expression

functionThe keyword can define a generator function inside the expression. The function declaration method (function keyword followed by Asterisk) will define a generator function (generator function), which returns a Generator object

Syntax: function* name([param[, param[, ... param]]]) { statements }

function* idMaker(){
  let index = 0;
  while(index<3)
    yield index++;
}

let gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
Copy after login

Receive parameters

function* idMaker(){
    let index = arguments[0] || 0;
    while(true)
        yield index++;
}

let gen = idMaker(5);
console.log(gen.next().value); // 5
console.log(gen.next().value); // 6
Copy after login

Pass parameters

function *createIterator() {
    let first = yield 1;
    let second = yield first + 2; // 4 + 2 
                                  // first =4 是next(4)将参数赋给上一条的
    yield second + 3;             // 5 + 3
}

let iterator = createIterator();

console.log(iterator.next());    // "{ value: 1, done: false }"
console.log(iterator.next(4));   // "{ value: 6, done: false }"
console.log(iterator.next(5));   // "{ value: 8, done: false }"
console.log(iterator.next());    // "{ value: undefined, done: true }"
Copy after login

Expression

let x = function*(y) {
   yield y * y;
};
Copy after login

Related recommendations:

Introduction to operators == and === in JavaScript_javascript skills

##javascript core language-expression and Operator

The above is the detailed content of Introduction to operators and expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template