【JavaScript】 细说JS数据处理方法,让你的数据表现出色如画

JavaScript(简称JS)是一种灵活和高效处理数据的脚本语言,尤其在网页开发中广泛应用。下面是JS常用的数据处理方法,让我们一起来了解一下吧!

  1. 字符串处理:

    • 获取字符串长度:使用字符串的length属性。📏
    • 字符串连接:使用+运算符或concat()方法。🔗
    • 字符串截取:使用substring()substr()slice()方法。✂️
    • 字符串查找:使用indexOf()lastIndexOf()startsWith()endsWith()includes()等方法。🔍
    • 字符串替换:使用replace()或正则表达式的replace()方法。🔄
    • 字符串分割:使用split()方法将字符串拆分成数组。🔀
  2. 数组处理:

    • 遍历数组:使用for循环、forEach()map()filter()reduce()等方法。🔄
    • 数组连接:使用concat()或扩展运算符...。🔗
    • 数组排序:使用sort()方法。🔢
    • 数组查找:使用indexOf()lastIndexOf()find()findIndex()等方法。🔍
    • 数组截取和添加元素:使用splice()slice()push()pop()unshift()shift()等方法。✂️➕
  3. 对象处理:

    • 属性访问:通过点号.或中括号[]来获取或设置对象的属性。🔑🔍
    • 遍历对象:使用for...in循环遍历对象的可枚举属性,或使用Object.keys()Object.values()Object.entries()等方法。🔄
    • 对象复制:使用深拷贝或浅拷贝的方法进行对象的复制操作。📝
  4. 数字处理:

    • 数字转换:使用parseInt()parseFloat()Number()等方法将字符串转换为数字。🔢
    • 数字格式化:使用toFixed()toPrecision()toExponential()等方法。💰
    • 数学计算:使用Math对象提供的方法,如Math.round()Math.floor()Math.ceil()Math.abs()等。➕➖✖️➗

说明&举例

  1. 字符串处理:

    • 获取字符串长度:使用字符串的length属性。

      let str = "Hello World";
      console.log(str.length); // 输出 11
      
    • 字符串连接:使用+运算符或concat()方法。

      let str1 = "Hello";
      let str2 = "World";
      console.log(str1 + " " + str2); // 输出 "Hello World"
      
      let str1 = "Hello";
      let str2 = " "
      let str3 = "World";
      let result = str1.concat(str2,str3)
      console.log(result); // 输出 "Hello World"
      
    • 字符串截取:使用substring()substr()slice()方法。

      let str = "Hello World";
      console.log(str.substring(0, 5)); // 输出 "Hello"
      console.log(str.substr(6, 5)); // 输出 "World"
      console.log(str.slice(-5)); // 输出 "World"
      
      1. substring(startIndex, endIndex) 方法:
      • 描述:返回一个新的字符串,包括从 startIndexendIndex - 1(不包括 endIndex)之间所有的字符。
      • 参数:
        • startIndex:必需,要提取的子字符串的起始位置的索引。如果是负数,则视为0。
        • endIndex:可选,要提取的子字符串的结束位置的索引。如果省略该参数,则提取到字符串的末尾。
      • 返回值:返回截取的子字符串。
      1. substr(startIndex, length) 方法:

        • 描述:返回一个新的字符串,从 startIndex 开始,长度为 length 的字符子串。
        • 参数:
          • startIndex:必需,要从该索引开始提取子字符串。如果是负数,则表示从末尾倒数索引。
          • length:可选,指定要提取的字符数。如果省略或超出字符串长度,则提取到字符串的末尾。
        • 返回值:返回截取的子字符串。
      2. slice(startIndex, endIndex) 方法:

        • 描述:返回一个新的字符串,包括从 startIndexendIndex - 1(不包括 endIndex)之间所有的字符。
        • 参数:
          • startIndex:可选,要提取的子字符串的起始位置的索引。如果是负数,则从末尾开始计数。
          • endIndex:可选,要提取的子字符串的结束位置的索引。如果省略该参数,则提取到字符串的末尾。
        • 返回值:返回截取的子字符串。

      这三个方法有一些区别:

      • substring() 方法将 startIndexendIndex 作为参数,并根据这两个索引提取字符。如果 startIndex 大于 endIndex,则交换这两个值。
      • substr() 方法将 startIndexlength 作为参数,并提取从 startIndex 开始指定长度的字符。
      • slice() 方法使用 startIndexendIndex 作为参数,并提取从 startIndexendIndex - 1(不包括 endIndex)之间的字符。
    • 字符串查找:使用indexOf()lastIndexOf()startsWith()endsWith()includes()等方法。

      let str = "Hello World";
      console.log(str.indexOf("o")); // 输出 4
      console.log(str.lastIndexOf("o")); // 输出 7
      console.log(str.startsWith("Hello")); // 输出 true
      console.log(str.endsWith("World")); // 输出 true
      console.log(str.includes("llo")); // 输出 true
      

      indexOf(searchValue, startIndex)​: 返回指定字符或子字符串在原字符串中从startIndex开始第一次出现的位置的索引。如果未找到,则返回-1。
      ​​lastIndexOf(searchValue, startIndex)​: 返回指定字符或子字符串在原字符串中从startIndex开始最后一次出现的位置的索引。如果未找到,则返回-1。
      ​​startsWith(searchValue, startIndex)​: 检查字符串是否以指定的字符或子字符串在startIndex位置开始。返回布尔值。 ​​》》。》。
      endsWith(searchValue, endIndex)​: 检查字符串是否以指定的字符或子字符串在endIndex位置结尾。返回布尔值。
      ​​includes(searchValue, startIndex)​: 检查字符串是否包含指定的字符或子字符串。返回布尔值。

    • 字符串替换:使用replace()或正则表达式的replace()方法。

      let str = "Hello World";
      console.log(str.replace("Hello", "Hi")); // 输出 "Hi World"
      console.log(str.replace(/o/g, "e")); // 输出 "Helle Werld"
      

      replace() 方法用于在字符串中替换指定的字符或子字符串。
      语法:string.replace(searchValue, replaceValue)
      参数:

      • searchValue:必需,要被替换的字符或子字符串。
      • replaceValue:必需,替换 searchValue 的新字符或子字符串。
        返回值:一个新的字符串,其中所有的 searchValue 都被 replaceValue 替换。

      注意事项:

      • replace() 方法只会替换第一个匹配到的字符或子字符串。如果需要替换所有匹配到的字符或子字符串,可以使用正则表达式,并且使用全局(g)标志。
      • replace() 方法不会修改原始字符串,而是返回一个新的字符串作为结果。
    • 字符串分割:使用split()方法将字符串拆分成数组。

      let str = "Hello,World";
      console.log(str.split(",")); // 输出 ["Hello", "World"]
      
  2. 数组处理:

    • 遍历数组:使用for循环、forEach()map()filter()reduce()等方法。
      let arr = [1, 2, 3];
      
      // 使用 for 循环遍历数组
      for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
      }
      
      // 使用 forEach() 方法遍历数组
      arr.forEach(function(item, index, array) {
        console.log(item);
      });
      
      // 使用 map() 方法遍历并修改数组
      let newArray = arr.map(function(item, index, array) {
        return item * 2;
      });
      
      // 使用 filter() 方法过滤数组元素
      let filteredArray = arr.filter(function(item, index, array) {
        return item > 1;
      });
      
      // 使用 reduce() 方法进行累加操作
      let sum = arr.reduce(function(previousValue, currentValue, currentIndex, array) {
        return previousValue + currentValue;
      });
      

    这是四个常用于数组的高阶函数,它们用于处理数组的元素,并提供了不同的功能和用途:

    1. forEach() 方法:

      • 描述:对数组的每个元素执行一次指定的函数。
      • 参数:接受一个回调函数作为参数,该函数将在数组的每个元素上被调用。
      • 返回值:没有返回值。
      • 特点:适合用于遍历数组并执行一些操作,例如打印数组元素或修改数组。
    2. map() 方法:

      • 描述:对数组的每个元素执行一次指定的函数,并返回一个新的数组,该数组包含函数的返回值。
      • 参数:接受一个回调函数作为参数,该函数将在数组的每个元素上被调用。
      • 返回值:返回一个新的数组,其中包含回调函数的返回值。
      • 特点:适合用于根据数组的每个元素生成一个新的数组。常用于数据转换、映射和提取特定属性的值等操作。
    3. filter() 方法:

      • 描述:使用指定的函数对数组的每个元素进行测试,并返回一个新的数组,其中包含测试通过的元素。
      • 参数:接受一个回调函数作为参数,该函数将在数组的每个元素上被调用,返回值为布尔类型(true 或 false)。
      • 返回值:返回一个新的数组,其中包含回调函数返回值为 true 的元素。
      • 特点:适合用于根据条件筛选数组中的元素。常用于过滤、筛选或查找符合特定条件的元素。
    4. reduce() 方法:

      • 描述:对数组的每个元素执行一次指定的归约函数,并将结果累加为单个值。
      • 参数:接受一个归约函数作为参数,该函数接受累加器和当前元素作为参数,并返回一个经过计算的值。
      • 返回值:返回最终累计的结果值。
      • 特点:适合用于对数组中的元素进行累加、求和、平均值等操作。

    这四个方法提供了更高层次的抽象,使代码更简洁和可读,并提高对数组的操作效率。根据具体需求和要求,选择适合的方法来处理数组操作。

    • 数组连接:使用concat()或扩展运算符...

      let arr1 = [1, 2, 3];
      let arr2 = [4, 5, 6];
      let concatenatedArray = arr1.concat(arr2); // 使用 concat() 方法
      console.log(concatenatedArray); // 输出 [1, 2, 3, 4, 5, 6]
      
      let combinedArray = [...arr1, ...arr2]; // 使用扩展运算符
      console.log(combinedArray); // 输出 [1, 2, 3, 4, 5, 6]
      
    • 数组排序:使用sort()方法。

      let arr = [3, 1, 2];
      arr.sort();
      console.log(arr); // 输出 [1, 2, 3]
      
    • 数组查找:使用indexOf()lastIndexOf()find()findIndex()等方法。

      let arr = [1, 2, 3];
      console.log(arr.indexOf(2)); // 输出 1
      console.log(arr.lastIndexOf(2)); // 输出 1
      
      let foundElement = arr.find(function(item, index, array) {
        return item > 1;
      });
      console.log(foundElement); // 输出 2
      
      let foundIndex = arr.findIndex(function(item, index, array) {
        return item > 1;
      });
      console.log(foundIndex); // 输出 1
      

      find(callback)​: 返回数组中满足条件的第一个元素。如果未找到,则返回undefined。
      ​​findIndex(callback)​: 返回数组中满足条件的第一个元素的索引。如果未找到,则返回-1。

    • 数组截取和添加元素:使用splice()slice()push()pop()unshift()shift()等方法。

      let arr = [1, 2, 3];
      let removedElements = arr.splice(1, 2); // 从索引 1 开始删除 2 个元素
      console.log(arr); // 输出 [1]
      console.log(removedElements); // 输出 [2, 3]
      
      let slicedArray = arr.slice(0, 2); // 截取索引 0 到 1 的部分
      console.log(slicedArray); // 输出 [1]
      
      arr.push(4); // 在末尾添加元素
      console.log(arr); // 输出 [1, 4]
      
      let poppedElement = arr.pop(); // 删除并返回末尾元素
      console.log(arr); // 输出 [1]
      console.log(poppedElement); // 输出 4
      
      arr.unshift(0); // 在开头添加元素
      console.log(arr); // 输出 [0, 1]
      
      let shiftedElement = arr.shift(); // 删除并返回开头元素
      console.log(arr); // 输出 [1]
      console.log(shiftedElement); // 输出 0
      
  3. 对象处理:

    • 属性访问:通过点号.或中括号[]来获取或设置对象的属性。

      let obj = {name: "John", age: 30};
      console.log(obj.name); // 输出 "John"
      console.log(obj["age"]); // 输出 30
      
      obj.name = "Peter"; // 设置属性值
      obj["age"] = 35;
      
    • 遍历对象:使用for...in循环遍历对象的可枚举属性,或使用Object.keys()Object.values()Object.entries()等方法。

      let obj = {name: "John", age: 30};
      
      // 使用 for...in 循环遍历对象的属性
      for (let key in obj) {
        console.log(key + ": " + obj[key]);
      }
      
      // 使用 Object.keys() 获取对象的属性数组
      let keys = Object.keys(obj);
      console.log(keys); // 输出 ["name", "age"]
      
      // 使用 Object.values() 获取对象的属性值数组
      let values = Object.values(obj);
      console.log(values); // 输出 ["John", 30]
      
      // 使用 Object.entries() 获取对象的键值对数组
      let entries = Object.entries(obj);
      console.log(entries); // 输出 [["name", "John"], ["age", 30]]
      
    • 对象复制:使用深拷贝或浅拷贝的方法进行对象的复制操作。

      // 浅拷贝
      let obj1 = {name: "John", age: 30};
      let obj2 = Object.assign({}, obj1);
      // or let obj2 = {...obj1};
      
      // 深拷贝(需要依赖外部库,如 lodash、jQuery)
      let deepCopyObj = _.cloneDeep(obj1); // 使用 lodash 库
      // or let deepCopyObj = jQuery.extend(true, {}, obj1); // 使用 jQuery
      
  4. 数字处理:

    • 数字转换:使用parseInt()parseFloat()Number()等方法将字符串转换为数字。

      let str = "123";
      console.log(parseInt(str)); // 输出 123
      
      let floatStr = "3.14";
      console.log(parseFloat(floatStr)); // 输出 3.14
      
      let numStr = "42";
      console.log(Number(numStr)); // 输出 42
      
    • 数字格式化:使用toFixed()toPrecision()toExponential()等方法。

      let num = 3.14159;
      console.log(num.toFixed(2)); // 输出 "3.14"
      console.log(num.toPrecision(3)); // 输出 "3.14"
      console.log(num.toExponential(2)); // 输出 "3.14e+0"
      
    • 数学计算:使用Math对象提供的方法,如 ​Math.round()​(四舍五入)、​Math.floor()​(向下取整)、​Math.ceil()​(向上取整)、​Math.abs()​(绝对值)等。

      console.log(Math.round(3.5)); // 输出 4
      console.log(Math.floor(3.9)); // 输出 3
      console.log(Math.ceil(3.1)); // 输出 4
      console.log(Math.abs(-4)); // 输出 4
      
    • 生成随机数:使用 ​Math.random()​和一系列数学计算方法生成随机数。

    • 数字范围限制:使用 ​Math.max()​和 ​Math.min()​方法限制数字的范围。

    • 数字比较:使用比较运算符(如 ​<​、​>​、​<=​、​>=​、​==、​ ​===​)进行数字之间的比较。

需要注意的是,以上只是简单示例,实际应用时需要根据具体情况做适当调整。

标签:#JavaScript #数据处理 #字符串处理 #数组处理 #对象处理 #数字处理

  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值