Python arsenal development-front-end JavaScript basic syntax (35)

Front-end JavaScript basic syntax (35)

JavaScript strings and common methods

A string in JavaScript is a sequence of zero or more characters, which can include letters, numbers, symbols, spaces, etc. Here are some commonly used string methods in JavaScript:

  1. length: Returns the length of the string, that is, the number of characters.
let str = "javascript";
console.log(str.length); // 10
  1. indexOf(): Returns the position where the specified string first appears in the original string, or -1 if not found.
let str = "hello world";
console.log(str.indexOf("world")); // 6
  1. slice(): Extracts characters within the specified range from the string and returns it as a new string
let str = "javascript";
console.log(str.slice(0, 4)); // java
  1. substring(): Extracts the characters in the specified range from the string and returns it as a new string. Similar to the slice() method, but does not support negative parameters.
let str = "javascript";
console.log(str.substring(0, 4)); // java
  1. substr(): Extracts the specified number of characters starting from the specified position in the string and returns it as a new string. Similar to the slice() method, but the second parameter indicates the number of characters to be extracted.
let str = "javascript";
console.log(str.substr(4, 6)); // script
  1. replace(): Replace specified characters in a string.
let str = "hello world";
console.log(str.replace("world", "javascript")); // hello javascript
  1. toUpperCase(): Convert string to uppercase letters
let str = "javascript";
console.log(str.toUpperCase()); // JAVASCRIPT
  1. toLowerCase(): Convert string to lowercase letters
let str = "JAVASCRIPT";
console.log(str.toLowerCase()); // javascript
  1. trim(): remove spaces at both ends of a string
let str = "  javascript  ";
console.log(str.trim()); // javascript
  1. toUpperCase and toLowerCase: Convert strings to uppercase or lowercase
const str = "Hello";
console.log(str.toUpperCase()); // "HELLO"
console.log(str.toLowerCase()); // "hello"
  1. charAt and charCodeAt: Return the character or character code at the specified position in the string
const str = "hello";
console.log(str.charAt(0)); // "h"
console.log(str.charCodeAt(0)); // 104
  1. concat: concatenate multiple strings together
const str1 = "hello";
const str2 = "world";
console.log(str1.concat(" ", str2)); // "hello world"
  1. split: Split a string into an array of strings
const str = "hello world";
console.log(str.split(" ")); // ["hello", "world"]

JavaScript arrays and common methods

An array in JavaScript is a data structure that can store multiple values, and these values ​​can be of different types. Here are some commonly used JavaScript array methods:

  1. push(): Adds a new element to the end of the array and returns the new length of the array.
let arr = [1, 2, 3];
arr.push(4);
console.log(arr);   // [1, 2, 3, 4]
  1. pop(): Removes an element from the end of the array and returns the value of the element.
let arr = [1, 2, 3];
let popped = arr.pop();
console.log(popped);   // 3
console.log(arr);      // [1, 2]
  1. shift(): removes an element from the beginning of the array and returns the value of the element
let arr = [1, 2, 3];
let shifted = arr.shift();
console.log(shifted);   // 1
console.log(arr);       // [2, 3]
  1. unshift(): Adds a new element to the beginning of the array and returns the new length of the array
let arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);  // [0, 1, 2, 3]
  1. slice(): Returns a new array containing the specified elements in the original array
let arr = [1, 2, 3, 4, 5];
let sliced = arr.slice(1, 4);
console.log(sliced);   // [2, 3, 4]
  1. splice(): Remove elements from an array and add new elements at the deleted location
let arr = [1, 2, 3, 4, 5];
arr.splice(1, 2, "a", "b");
console.log(arr);  // [1, "a", "b", 4, 5]
  1. reverse() method: reverse the order of elements in the array and return the original array
let arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
  1. sort() method: Sort the array in alphabetical or numerical order and return the original array
let arr = [5, 1, 4, 2, 3];
arr.sort();
console.log(arr); // [1, 2, 3, 4, 5]
  1. forEach() method: Execute the specified function on each element in the array in sequence
let arr = [1, 2, 3];
arr.forEach(function(item, index, array) {
    
    
  console.log(item, index, array);
});

JavaScript type conversion

There are many types of type conversion methods in JavaScript, including:

  • Explicit type conversion (forced type conversion): Use specific functions or operators to convert one data type to another data type, such as Number(), String(), Boolean(), etc.
  • Implicit type conversion (automatic type conversion): Automatically convert one data type to another data type at runtime, such as addition operations of strings and numbers, comparison of Boolean values ​​and numbers, etc.

Here are some common type conversion examples:

  1. Convert string to number:
var str = "123";
var num = Number(str);
console.log(num); // 123
  1. Number to string:
var num = 123;
var str = String(num);
console.log(str); // "123"
  1. Convert string to boolean:
var str = "hello";
var bool = Boolean(str);
console.log(bool); // true

var str2 = "";
var bool2 = Boolean(str2);
console.log(bool2); // false
  1. Convert numbers to Boolean values:
var num = 0;
var bool = Boolean(num);
console.log(bool); // false

var num2 = 10;
var bool2 = Boolean(num2);
console.log(bool2); // true
  1. Convert Boolean value to number:
var bool = true;
var num = Number(bool);
console.log(num); // 1

var bool2 = false;
var num2 = Number(bool2);
console.log(num2); // 0

JavaScript closures

Closure refers to the feature in JavaScript that inner functions can access the scope of their outer functions. Simply put, a function returns another function, and the latter can access the variables of the former, forming a closure.

Closures have two main characteristics:

  1. An inner function can access variables in the scope of its outer function, including variables that persist after the outer function has completed execution.

  2. The variables of the outer function can be accessed by the inner function, but the variables of the inner function cannot be accessed by the outside.

Common uses of closures include:

  1. Partially applied functions: Fix some parameters of the function and generate new functions for easy reuse.

  2. Encapsulating variables: Encapsulating variables through closures can avoid global pollution of data and protect data security at the same time.

  3. Asynchronous operations: Use closures to save values ​​that need to be used in asynchronous functions during asynchronous operations.

For example:

function outerFunction() {
    
    
  var outVar = "I'm outer";
  function innerFunction() {
    
    
    console.log(outVar); 
  }
  return innerFunction;
}
var inner = outerFunction();
inner(); // 输出 "I'm outer"

In the above example, innerFunction() accesses the variable outVar of outerFunction(), and since innerFunction() is called externally as the return value of outerFunction(), outVar is encapsulated in the closure of innerFunction(). At this time, even if outerFunction() ) is executed, outVar still exists in memory.

Here is a simple closure example:

function outerFunction(x) {
    
    
  function innerFunction(y) {
    
    
    return x + y;
  }
  return innerFunction;
}

let inner = outerFunction(5);
console.log(inner(3)); // 输出 8

In this example, outerFunction returns the innerFunction function, so we can store it in the variable inner. Then we call inner(3), which returns the result 8 of 5 + 3. Note that the x variable here is defined inside outerFunction, but it is still available inside innerFunction. This is a closure.

JavaScript object-oriented

JavaScript is an object-oriented programming language that supports object-oriented features such as objects, classes, inheritance, and polymorphism.

  1. Object: An object in JavaScript is a data structure composed of key-value pairs. The properties and methods of the object can be accessed through the . and [] operators.
var person = {
    
    
  name: "Tom",
  age: 20,
  sayHello: function() {
    
    
    console.log("Hello, my name is " + this.name);
  }
};
person.sayHello(); //输出:Hello, my name is Tom
  1. Class: A class in JavaScript is an object template created through a constructor that allows code reuse through prototypal inheritance.
function Person(name, age) {
    
    
  this.name = name;
  this.age = age;
}
Person.prototype.sayHello = function() {
    
    
  console.log("Hello, my name is " + this.name);
};
var person = new Person("Tom", 20);
person.sayHello(); //输出:Hello, my name is Tom
  1. Inheritance: Inheritance in JavaScript is based on the prototype chain. Subclasses can obtain the properties and methods of the parent class through the prototype chain.
function Student(name, age, grade) {
    
    
  Person.call(this, name, age);
  this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayHello = function() {
    
    
  console.log("Hello, my name is " + this.name + " and I'm in grade " + this.grade);
};
var student = new Student("Jack", 18, 12);
student.sayHello(); //输出:Hello, my name is Jack and I'm in grade 12
  1. Polymorphism: Polymorphism in JavaScript is achieved through function overloading. Different functions can be called according to the type and number of parameters passed in.
function add(x, y) {
    
    
  if (typeof x === "number" && typeof y === "number") {
    
    
    return x + y;
  } else if (typeof x === "string" && typeof y === "string") {
    
    
    return x.concat(y);
  } else {
    
    
    throw new TypeError("Unsupported operand types");
  }
}
console.log(add(1, 2)); //输出:3
console.log(add("Hello, ", "world!")); //输出:Hello, world!

JavaScript DOM

DOM (Document Object Model) refers to a programming interface that represents document content. It represents an HTML or XML document as a tree structure and maps each node in the tree to an object. The DOM allows developers to use JavaScript to manipulate various parts of the document, including elements, attributes, and text.

In JavaScript, you can access the DOM by using the document object. The document object represents the window or frame of the currently loaded document. It provides some methods and properties that allow developers to access and manipulate elements and properties in the document. For example, you can use the document.getElementById() method to get an element with a specified ID, or use the document.createElement() method to create a new element.

Here are some common DOM operations:

  1. Get element

You can use the document.getElementById() method to get the element with the specified ID, or the document.querySelector() method to get the first element that matches the specified selector, or the document.querySelectorAll() method to get all elements that match the specified selector.

For example:

var element = document.getElementById("my-element");
var element = document.querySelector(".my-class");
var elements = document.querySelectorAll("p");
  1. Manipulate the attributes or content of an element

You can get the value of a specified attribute using the element.getAttribute() method, set the value of a specified attribute using the element.setAttribute() method, or access or set the content of an element using the element.innerHTML property.

For example:

var value = element.getAttribute("data-my-attribute");
element.setAttribute("data-another-attribute", "value");
element.innerHTML = "New content";
  1. Manipulate the style of the element

You can access or set an element's style properties using the element.style property.

For example:

element.style.backgroundColor = "red";
element.style.display = "none";

These are some basic DOM operations, but the DOM API is very large. For specific operation methods, you can refer to relevant documents or tutorials.

JavaScriptBOM

BOM (Browser Object Model) refers to the browser object model, which is an important part of JavaScript and is used to operate browser windows and screens. The BOM provides a set of objects and methods that allow JavaScript code to interact with the browser. Common BOM objects include:

  1. Window object: represents the window or tab in the browser. It contains all properties and methods of the browser window, such as location, history, document, alert, etc.

  2. Navigator object: Provides information about the browser, such as browser type, version, language, operating system, etc.

  3. screen object: Provides information about the user's screen, such as the screen's width, height, pixel density, etc.

  4. History object: Provides information about the browser history, such as the position of the current page in the browser history. You can use the back, forward, and go methods to move forward, backward, or jump in the history.

  5. Location object: Provides information about the current document, such as the URL, protocol, host name, path, etc. of the current document. You can use the assign, reload, and replace methods to change the URL of the current document.

In addition to the above commonly used objects and methods, there are some other objects and methods in the BOM, such as alert, confirm, prompt and other methods used to interact with users, as well as setTimeout, setInterval and other methods used to implement scheduled tasks.

BOM (Browser Object Model) is a collection of objects and methods in JavaScript that interact with browser windows and frames. Here are some common examples in BOMs:

  1. Window object: represents the browser window or frame
var newWindow = window.open('http://www.example.com', 'example', 'width=500,height=500');
newWindow.close(); //关闭新窗口
  1. Navigator object: provides information about the browser, such as browser name 2 and version number
console.log(navigator.userAgent); //输出浏览器名称和版本号
  1. Location object: Provides the URL information of the current document
console.log(location.href); //输出当前URL
location.reload(); //重新加载当前文档
  1. History object: Provides information about the history of the browser window
history.back(); //返回上一页
history.forward(); //前往下一页
  1. Screen object: provides information about the user's screen
console.log(screen.width); //输出屏幕宽度
console.log(screen.height); //输出屏幕高度

Guess you like

Origin blog.csdn.net/qq_64973687/article/details/134679480