2025年3月14日 星期五 甲辰(龙)年 月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

JavaScript 中的 Math 对象与字符串操作详解

时间:02-05来源:作者:点击数:27

前言

本文将详细介绍 JavaScript 中 Math 对象和字符串操作的相关知识,并通过具体的代码示例进行解析。希望通过本文的学习,读者能够更加深入地理解这些基础知识,并将其应用到实际开发中。

一、Math 对象

Math 对象是 JavaScript 中内置的一个对象,提供了各种数学常量和函数,用于执行常见的数学运算。以下是 Math 对象的一些常用方法及其用法:

1. 圆周率 Math.PI
  • console.log(Math.PI); // 输出圆周率 π 的值
2. 求绝对值 Math.abs()
  • console.log(Math.abs(-3)); // 输出 3

Math.abs() 方法返回一个数的绝对值,即去掉符号后的数值。

3. 四舍五入 Math.round()
  • console.log(Math.round(4.5)); // 输出 5
  • console.log(Math.round(4.4)); // 输出 4
  • console.log(Math.round(-4.5)); // 输出 -4
  • console.log(Math.round(-4.5001)); // 输出 -5
  • console.log(Math.round(-4.9)); // 输出 -5
  • console.log(Math.round(-4.1)); // 输出 -4

Math.round() 方法对一个数进行四舍五入,返回最接近的整数。

4. 向上取整 Math.ceil()
  • console.log(Math.ceil(4.1)); // 输出 5
  • console.log(Math.ceil(4.9)); // 输出 5
  • console.log(Math.ceil(-4.1)); // 输出 -4
  • console.log(Math.ceil(-4.9)); // 输出 -4

Math.ceil() 方法对一个数向上取整,即返回大于或等于该数的最小整数。

5. 向下取整 Math.floor()
  • console.log(Math.floor(4.1)); // 输出 4
  • console.log(Math.floor(4.9)); // 输出 4
  • console.log(Math.floor(-4.1)); // 输出 -5
  • console.log(Math.floor(-4.9)); // 输出 -5

Math.floor() 方法对一个数向下取整,即返回小于或等于该数的最大整数。

6. 求最大值 Math.max() 和最小值 Math.min()
  • console.log(Math.max(4, 2, 6, 5, 3)); // 输出 6
  • console.log(Math.min(4, 2, 6, 5, 3)); // 输出 2
  • var arr = [4, 2, 6, 5, 3];
  • console.log(Math.max.apply(null, arr)); // 输出 6
  • console.log(Math.min.apply(null, arr)); // 输出 2
  • console.log(Math.max(...arr)); // 输出 6
  • console.log(Math.min(...arr)); // 输出 2

Math.max() 和 Math.min() 方法分别返回一组数中的最大值和最小值。对于数组,可以使用 apply 或展开运算符 ... 来传递参数。

7. 求幂 Math.pow()
  • console.log(Math.pow(2, 32)); // 输出 4294967296
  • console.log(Math.pow(2, 64)); // 输出 1.8446744073709552e+19

Math.pow() 方法返回指定底数的指数次幂。

8. 求平方根 Math.sqrt()
  • console.log(Math.sqrt(9)); // 输出 3

Math.sqrt() 方法返回一个数的平方根。

二、字符串操作

字符串是 JavaScript 中最基本的数据类型之一,广泛应用于文本处理、用户输入验证等场景。以下是一些常用的字符串操作方法及其用法:

1. 创建字符串
  • var str = 'hello';
  • var o_str = new String('world');
  • console.log(typeof str, typeof o_str); // 输出 'string' 'object'

可以通过直接赋值或使用 String 构造函数创建字符串。需要注意的是,直接赋值创建的是原始类型的字符串,而使用构造函数创建的是对象类型的字符串。

2. 字符串属性
  • var str = '前端青山';
  • console.log(str.length); // 输出 7

length 属性返回字符串的长度,即字符的数量。

3. 字符串方法
3.1 查找子字符串
  • var str = 'how do you do';
  • console.log(str.indexOf('do')); // 输出 4
  • console.log(str.indexOf('do', 5)); // 输出 11
  • console.log(str.lastIndexOf('do')); // 输出 11
  • console.log(str.lastIndexOf('do', 10)); // 输出 4
  • console.log(str.lastIndexOf('do', '4')); // 输出 4
  • console.log(str.lastIndexOf('do', 3)); // 输出 -1

indexOf() 和 lastIndexOf() 方法分别从前往后和从后往前查找子字符串的位置。如果未找到,则返回 -1

3.2 遍历字符串
  • var str = 'how are you';
  • for (var i = 0, len = str.length; i < len; i++) {
  • console.log(str.charAt(i));
  • }

charAt() 方法返回指定位置的字符。可以通过循环遍历整个字符串。

3.3 获取字符编码
  • var str = 'abc';
  • console.log(str.charCodeAt(0) + 1); // 输出 98
  • console.log(String.fromCharCode(str.charCodeAt(0) + 1)); // 输出 'b'

charCodeAt() 方法返回指定位置字符的 Unicode 编码值。String.fromCharCode() 方法根据编码值返回对应的字符。

3.4 替换子字符串
  • var str = 'how do you do';
  • console.log(str.replace('do', 'de')); // 输出 'how de you do'
  • console.log(str.replaceAll('do', 'de')); // 输出 'how de you de'

replace() 方法替换第一个匹配的子字符串,replaceAll() 方法替换所有匹配的子字符串。

3.5 提取子字符串
  • var str = 'how do you do';
  • console.log(str.substring(4, 6)); // 输出 'do'
  • console.log(str.substr(4, 6)); // 输出 'do you'
  • console.log(str.slice(4, 6)); // 输出 'do'
  • console.log(str.substring(6, 4)); // 输出 'do'
  • console.log(str.slice(6, 4)); // 输出 ''
  • console.log(str.substring(-6, -4)); // 输出 ''
  • console.log(str.slice(-6, -4)); // 输出 'yo'

substring()substr() 和 slice() 方法都可以提取子字符串。其中,substring() 支持参数互换,slice() 支持负数索引。

3.6 字符串转换
  • var str = 'How Are You';
  • console.log(str.toUpperCase()); // 输出 'HOW ARE YOU'
  • console.log(str.toLowerCase()); // 输出 'how are you'
  • var arr = str.split(' ', 5); // ['How', 'Are', 'You']
  • console.log(arr);
  • console.log(str.split('o')); // ['H', 'w Are Y', 'u']
  • console.log(str.split('')); // ['H', 'o', 'w', ' ', 'A', 'r', 'e', ' ', 'Y', 'o', 'u']
  • console.log(str.split(' ', 2)); // ['How', 'Are']
  • console.log(str.split('oo')); // ['How Are You']

toUpperCase() 和 toLowerCase() 方法分别将字符串转换为大写和小写。split() 方法根据指定分隔符将字符串分割成数组。

3.7 字符串连接
  • var str = 'hello';
  • console.log(str.concat(' world')); // 输出 'hello world'

concat() 方法用于连接两个或多个字符串。

3.8 去除空白字符
  • var str = ' a b ';
  • console.log('(' + str.replaceAll(' ', '') + ')'); // 输出 '(ab)'
  • console.log('(' + str.trim() + ')'); // 输出 '(a b)'
  • console.log('(' + str.trimStart() + ')'); // 输出 '(a b )'
  • console.log('(' + str.trimEnd() + ')'); // 输出 '( a b)'

trim() 方法去除字符串两端的空白字符,trimStart() 和 trimEnd() 分别去除左端和右端的空白字符。

3.9 自定义去除空白字符
  • function fnRemoveAllSpace(str) {
  • while (str.indexOf(' ') !== -1) {
  • str = str.replace(' ', '');
  • }
  • return str;
  • }
  • console.log('(' + fnRemoveAllSpace(' a b ') + ')'); // 输出 '(ab)'

自定义函数 fnRemoveAllSpace() 通过循环替换空格来去除字符串中的所有空白字符。

3.10 自定义去除两端空白字符
  • function fnTrim(str) {
  • while (str.charAt(0) === ' ') {
  • str = str.replace(' ', '');
  • }
  • var arr = str.split('');
  • while (arr[arr.length - 1] === ' ') {
  • arr.pop();
  • }
  • return arr.join('');
  • }
  • console.log('(' + fnTrim(' a b ') + ')'); // 输出 '(a b)'

自定义函数 fnTrim() 通过遍历字符串并去除两端的空白字符。

3.11 统计字母数量
  • function countNum(str) {
  • var uppercase = 0;
  • var lowercase = 0;
  • for (var i = 0, len = str.length; i < len; i++) {
  • var ch = str.charAt(i);
  • if (ch >= 'A' && ch <= 'Z') {
  • uppercase++;
  • } else if (ch >= 'a' && ch <= 'z') {
  • lowercase++;
  • }
  • }
  • console.log('大写字母有:' + uppercase + '个\n小写字母有:' + lowercase + '个');
  • }
  • countNum('How Are You');

countNum() 函数统计字符串中大写字母和小写字母的数量。

3.12 成绩求和
在这里插入图片描述
在这里插入图片描述
  • var o_txt = document.getElementById('txt');
  • var o_btn = document.getElementById('btn');
  • function fn() {
  • var info = o_txt.value;
  • var arr = info.split(',');
  • var sum = arr.reduce(function (prev, next) {
  • return Number(prev) + Number(next);
  • });
  • o_txt.value = sum;
  • }
  • o_btn.onclick = fn;

通过用户输入的成绩字符串,将其转换为数组并求和。

3.13 影响职业因素计算
在这里插入图片描述
  • var o_txt = document.getElementById('txt');
  • var o_result = document.getElementById('result');
  • var o_submit = document.getElementById('submit');
  • var o_reset = document.getElementById('reset');
  • function fnJob() {
  • var sum = 0;
  • var str = '';
  • var info = o_txt.value;
  • var letter = ' abcdefghijklmnopqrstuvwxyz';
  • for (var i = 0, infoLen = info.length; i < infoLen; i++) {
  • for (var j = 0, letterLen = letter.length; j < letterLen; j++) {
  • if (info.charAt(i) === letter.charAt(j)) {
  • sum += j;
  • str += j + '+';
  • }
  • }
  • }
  • o_result.innerText = str.slice(0, -1) + '=' + sum;
  • }
  • function fnclear() {
  • o_txt.value = o_result.innerText = '';
  • }
  • o_submit.onclick = fnJob;
  • o_reset.onclick = fnclear;

计算单词中每个字母在字母表中的位置之和,并显示结果。

结尾

通过本文的介绍,我们详细探讨了 JavaScript 中 Math 对象和字符串操作的各种方法及其应用场景。希望读者能够掌握这些基础知识,并在实际开发中灵活运用。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐