Javascript作为一门脚本语言已经成为了Web应用开发领域的标配,而内置对象则是Javascript中最为重要的特征之一。在Javascript中,我们可以通过调用内置对象来实现各种各样的功能,包括操作字符串、数组、日期等等。这篇文章将重点介绍Javascript中常用的一些内置对象,并配以实例说明。
1. String对象
//创建字符串 var str1 = "Hello World!"; var str2 = new String("How are you?"); //字符串长度 console.log(str1.length); //输出:12 //字符串截取 console.log(str1.substring(6)); //输出:World! console.log(str2.slice(4, 7)); //输出:are console.log(str1.substr(1,4)); //输出:ello //字符串查找 console.log(str1.indexOf("o")); //输出:4 console.log(str1.lastIndexOf("l")); //输出:9 //字符串替换 console.log(str2.replace("you", "I")); //输出:How are I? //字符串大小写转换 console.log(str1.toUpperCase()); //输出:HELLO WORLD! console.log(str2.toLowerCase()); //输出:how are you?
2. Array对象
//创建数组 var arr1 = ["apple", "orange", "banana"]; var arr2 = new Array(3); arr2[0] = "red"; arr2[1] = "green"; arr2[2] = "blue"; //数组合并 var arr3 = arr1.concat(arr2); console.log(arr3); //输出:["apple", "orange", "banana", "red", "green", "blue"] //数组排序 console.log(arr1.sort()); //输出:["apple", "banana", "orange"] //数组反转 console.log(arr3.reverse()); //输出:["blue", "green", "red", "banana", "orange", "apple"] //数组查找 console.log(arr3.indexOf("orange")); //输出:4 console.log(arr2.lastIndexOf("blue")); //输出:2 //数组截取 console.log(arr1.slice(1,2)); //输出:["orange"] //数组删除、添加元素 var arr4 = arr1.splice(1, 1, "pear", "grape"); console.log(arr1); //输出:["apple", "pear", "grape", "banana"] console.log(arr4); //输出:["orange"]
3. Date对象
//创建日期对象 var date1 = new Date(); var date2 = new Date("2022-12-31"); var date3 = new Date(2022, 11, 31); //获取日期 console.log(date1); //输出当前日期 //日期格式转换 console.log(date1.toDateString()); //输出:Sun Jul 25 2021 console.log(date1.toTimeString()); //输出:23:53:07 GMT+0800 (中国标准时间) console.log(date1.toLocaleDateString()); //输出:2021/7/25 console.log(date1.toLocaleTimeString()); //输出:23:53:07 //日期计算 console.log(date2.getTime() - date1.getTime()); //输出相差的时间毫秒数 //日期比较 console.log(date2 >date1); //输出:true //日期设置 date1.setFullYear(2022); console.log(date1.toLocaleDateString()); //输出:2022/7/25
4. Math对象
//常量 console.log(Math.PI); //输出:3.141592653589793 //数值计算 console.log(Math.pow(2,3)); //输出:8 console.log(Math.sqrt(4)); //输出:2 console.log(Math.abs(-5)); //输出:5 console.log(Math.ceil(2.1)); //输出:3 console.log(Math.floor(2.9)); //输出:2 console.log(Math.round(2.5)); //输出:3 console.log(Math.random()); //输出0到1之间的随机数
以上是Javascript中常用的一些内置对象,当然还有诸如RegExp、Boolean、Error等对象,这里就不再一一列举。通过学习和了解这些内置对象,我们可以更加轻松地运用Javascript来实现所需要的功能。