Table of Contents
1. Unary operator
1.delete operator
2.typeof operator
3.void operator
2. Relational operators
1.in operator
2.instanceof operator
3. Expression
1.this
2.super
3.new
4. Expansion syntax
5. Class expression
6. Function expression
7.function*Expression
Home Web Front-end JS Tutorial Introduction to operators and expressions in JavaScript

Introduction to operators and expressions in JavaScript

Sep 11, 2018 pm 05:01 PM
javascript

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles