JavaScript is a programming language widely used in web development. It provides many built-in functions and methods for working with various data types such as strings, mathematical operations, arrays, objects, dates and times. In this article, we will discuss some important internal methods of JavaScript.
1. String method
Example:
let str = "Hello World!"; let result = str.indexOf("World"); console.log(result); // 输出6
Example:
let str = "Hello World!"; let result = str.slice(0, 5); console.log(result); // 输出Hello
Example:
let str = "Hello World!"; let result = str.replace("World", "JavaScript"); console.log(result); // 输出Hello JavaScript!
2. Mathematical methods
Example:
let num = 3.141592654; let result = Math.round(num); console.log(result); // 输出3
Example:
let num = 3.141592654; let result = Math.floor(num); console.log(result); // 输出3
Example:
let result = Math.random(); console.log(result); // 输出0到1之间的随机数
3. Array method
Example:
let array = [1, 2, 3]; let result = array.push(4, 5); console.log(array); // 输出[1, 2, 3, 4, 5] console.log(result); // 输出5
Example:
let array = [1, 2, 3]; let result = array.pop(); console.log(array); // 输出[1, 2] console.log(result); // 输出3
Example:
let array = [1, 2, 3, 4, 5]; let result = array.splice(2, 2, 6, 7); console.log(array); // 输出[1, 2, 6, 7, 5] console.log(result); // 输出[3, 4]
4. Object method
Example:
let obj = { name: "Tom", age: 18, gender: "Male" }; let result = Object.keys(obj); console.log(result); // 输出[name, age, gender]
Example:
let obj = { name: "Tom", age: 18, gender: "Male" }; let result = Object.values(obj); console.log(result); // 输出[Tom, 18, Male]
Example:
let target = { name: "Alice", age: 20 }; let source = { name: "Bob", gender: "Male" }; let result = Object.assign(target, source); console.log(result); // 输出{name: "Bob", age: 20, gender: "Male"}
5. Date and time methods
Example:
let now = new Date(); console.log(now); // 输出表示当前时间的Date对象
Example:
let timestamp = Date.parse("2022-01-01T00:00:00"); console.log(timestamp); // 输出所表示日期时间的毫秒级时间戳
Example:
let now = new Date(); let year = now.getFullYear(); console.log(year); // 输出当前年份
The above introduces several internal methods of JavaScript, which are important tools for writing JavaScript programs. Mastering these methods will not only help improve programming efficiency, but also help write more efficient code. In practical applications, we should choose appropriate methods according to specific needs and use them rationally.
The above is the detailed content of javascript internal method. For more information, please follow other related articles on the PHP Chinese website!