To understand the commonly used built-in objects of JS, you need specific code examples
JavaScript (JS for short) is a scripting language that is widely used in web development and other fields. In JS, built-in objects refer to objects that have been defined within the language and can be directly called and used by developers. It is very necessary for developers to be familiar with and understand the commonly used built-in objects in JS. This article will introduce some commonly used JS built-in objects and give corresponding code examples.
Sample code:
// 计算平方根 var number = Math.sqrt(16); console.log(number); // 输出4 // 计算绝对值 var absoluteValue = Math.abs(-5); console.log(absoluteValue); // 输出5 // 计算随机数 var randomNum = Math.random(); console.log(randomNum); // 输出0-1之间的随机数
Sample code:
// 获取当前日期和时间 var currentDate = new Date(); console.log(currentDate); // 输出当前日期和时间 // 获取当前年份 var currentYear = currentDate.getFullYear(); console.log(currentYear); // 输出当前年份 // 格式化日期 var formattedDate = currentDate.toLocaleDateString(); console.log(formattedDate); // 输出格式化后的日期
Sample code:
// 获取字符串长度 var str = "Hello World"; var length = str.length; console.log(length); // 输出11 // 截取子字符串 var subStr = str.substring(0, 5); console.log(subStr); // 输出Hello // 转换为大写 var uppercaseStr = str.toUpperCase(); console.log(uppercaseStr); // 输出HELLO WORLD
Sample code:
// 定义数组 var arr = [1, 2, 3, 4, 5]; // 添加元素 arr.push(6); console.log(arr); // 输出[1, 2, 3, 4, 5, 6] // 删除元素 arr.pop(); console.log(arr); // 输出[1, 2, 3, 4, 5] // 遍历数组 arr.forEach(function (item) { console.log(item); });
Sample code:
// 正则表达式匹配 var str = "Hello World"; var pattern = /W/; var result = pattern.test(str); console.log(result); // 输出true // 正则表达式替换 var newStr = str.replace(pattern, "J"); console.log(newStr); // 输出Hello Jorld
The above are simple examples of some commonly used JS built-in objects. By understanding and learning these built-in objects, you can better handle operations such as math, dates, strings, arrays, and regular expressions in JS. Of course, the built-in objects of JS have more functions and usages. It is recommended that developers study and practice in depth to enrich their programming skills.
The above is the detailed content of Master common JS built-in objects. For more information, please follow other related articles on the PHP Chinese website!