Home > Article > Web Front-end > Various methods in javascript
JavaScript is a programming language used to add dynamic effects and interactivity to web pages. It has many useful methods for manipulating elements in web pages, working with strings and values, creating time intervals and animation effects, and more. In this article, we will discuss some important methods in JavaScript, along with their usage and examples.
1. String method
Example:
let string = "Hello World";
console.log(string.length); // The output result is: 11
Example:
let string = "Hello World";
console.log(string.charAt(3)); // The output result is: 'l'
Example:
let string1 = "Hello";
let string2 = "World";
console.log(string1.concat(" ", string2)); / / The output result is: "Hello World"
Example:
let string = "Hello World";
console.log(string.indexOf("o")); // The output result is: 4
Example:
let string = "Hello World";
console.log(string.replace("World", "JavaScript")); // The output result is: " Hello JavaScript"
Example:
let string = "Hello World";
console.log(string.slice(1, 5)); // The output result is: "ello"
2. Array method
Example:
let array = [1, 2, 3, 4, 5];
console.log(array.length); // The output result is: 5
Example:
let array = [1, 2, 3, 4, 5];
console.log(array.push(6)); // The output result is: 6
Example:
let array = [1, 2, 3, 4, 5];
console.log(array.pop()); // The output result is: 5
Example:
let array = [1, 2, 3, 4, 5];
console.log(array.join(",")); // Output results It is: "1,2,3,4,5"
Example:
let array = [1, 2, 3, 4, 5];
array.splice(2, 0, "a", "b");
console.log(array); //The output result is: [1, 2, "a", "b", 3, 4, 5]
Example:
let array = [3, 1, 4, 2, 5];
console.log(array.sort()); // The output result is: [ 1, 2, 3, 4, 5]
3. Numerical method
Example:
let num = 123;
console.log(num.valueOf()); // The output result is: 123
Example:
let num = 123;
console.log(num.toString()); // The output result is: "123"
Example:
let num = 3.14159;
console.log(num.toFixed(2)); // The output result is: "3.14"
Example:
let string = "123";
console.log(parseInt(string)); // The output result is: 123
Example:
let string = "3.14159";
console.log(parseFloat(string)); // The output result is: 3.14159
4. Event Method
Example:
let button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("Hello World");
});
Example:
let button = document.querySelector("button");
function handleClick() {
console.log("Hello World");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
The above are some commonly used methods in JavaScript. Of course there are many other methods, but mastering the above methods can help us become more comfortable in web development.
The above is the detailed content of Various methods in javascript. For more information, please follow other related articles on the PHP Chinese website!