常用内置对象
1、String(常用于处理字符串)
charAt(index)
:获取指定位置的字符。
js
const str = "Hello";
console.log(str.charAt(1)); // 输出: "e"
indexOf(searchValue, fromIndex)
:返回指定值首次出现的索引,如果未找到返回-1
。
js
const str = "Hello, World!";
console.log(str.indexOf("World")); // 输出:7
console.log(str.indexOf("Moon")); // 输出:-1
replace(searchValue, replacement)
:替换字符串中的内容,返回新字符串。searchValue
可以是字符串或正则表达式。
js
const str = "Hello World";
console.log(str.replace("World", "JavaScript")); // 输出: "Hello JavaScript"
substring(start, end)
:截取字符串。split(separator)
:将字符串分割为数组。toUpperCase()
、toLowerCase()
:转换大小写。trim()
:去除字符串两端的空白字符。
2、Array(处理数组)
push(element)
:在数组末尾添加一个或多个元素,并返回新数组的长度
js
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // 输出: [1, 2, 3, 4]
pop()
:删除并返回数组的最后一个元素
js
const arr = [1, 2, 3];
console.log(arr.pop()); // 输出: 3
console.log(arr); // 输出: [1, 2]
map(callback)
:对数组的每一个元素执行回调函数,并返回一个新数组
js
const arr = [1, 2, 3];
const newArr = arr.map(x => x * 2);
console.log(newArr); // 输出: [2, 4, 6]
filter(callback)
:返回一个新数组,包含通过回调函数测试的元素
js
const arr = [1, 2, 3, 4];
const filteredArr = arr.filter(x => x > 2);
console.log(filteredArr); // 输出: [3, 4]
shift()
、unshift()
:在数组开头删除或添加元素。slice()
、splice()
:截取或修改数组。find()
、findIndex()
:查找数组中的元素。reduce()
:对数组中的元素进行累积计算。
3、Date(处理日期和时间)
new Date()
:创建当前日期对象。getFullYear()
:返回日期的年份(四位数)
js
const date = new Date();
console.log(date.getFullYear()); // 输出: 当前年份(如 2023)
getMonth()
:返回日期的月份(0到11,0表示1月)
js
const date = new Date();
console.log(date.getMonth()); // 输出: 当前月份(如 9 表示 10 月)
getHours()
、getMinutes()
、getSeconds()
:获取时、分、秒。toISOString()
:将日期转换为 ISO 格式字符串。
4、Math(提供数学运算的属性和方法)
Math.random()
:返回一个0到1之间的随机数(包含0,不包含1)Math.floor()
:返回小于或者等于指定数字的最大整数(向下取整)Math.ceil()
、Math.round()
:向上取整、四舍五入。Math.max()
、Math.min()
:返回最大值或最小值。Math.pow(x, y)
:返回 x 的 y 次幂。Math.sqrt(x)
:返回 x 的平方根。
全局对象(global objects)与属性
常见的全局对象属性和方法:
undefined
:表示未定义的值。Infinity
:表示无穷大的值。NaN
:表示非数字值。eval()
:将字符串作为代码执行。setTimeout()
:在指定的延迟后执行函数。clearTimeout()
:取消setTimeout
设置的定时器。setInterval()
:每隔指定的时间间隔执行函数。clearInterval()
:取消setInterval
设置的定时器。
常见布局方法
parseInt(string)
:将字符串转换为整数。parseFloat(string)
:将字符串转换为浮点数。isNaN(value)
:检查值是否为NaN
。eval(string)
:执行字符串中的 JavaScript 代码(不推荐使用,存在安全隐患)。
JSON对象
JSON
是 JavaScript 中用于处理 JSON 格式数据的对象。
JSON.parse(string)
:解析字符串为对象
js
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 输出: "John"
JSON.stringify()
:序列化对象为字符串。
js
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // 输出: '{"name":"John","age":30}'
window对象
在浏览器环境中,window
是全局对象,所有全局变量和函数都是 window
对象的属性和方法。
常见属性和方法
window.console.log()
:输出日志。window.document
:操作 DOM。window.localStorage
:存储本地数据。window.setTimeout()
:设置定时器。
总结
- 全局对象 :在浏览器中是
window
,在 Node.js 中是global
。 - JSON :
JSON.parse()
和JSON.stringify()
是处理 JSON 数据的常用方法。 window
对象:浏览器环境中的全局对象,提供了许多实用的属性和方法。