前言

昨天联调一个页面,看着就一个页面,接口倒是不少。

  1. 热点问题配置测试联调完成(同步异步接口共11个)
  2. 1.配置新增
  3. 2.配置编辑
  4. 3.配置删除
  5. 4.热点问题新增
  6. 5.热点问题编辑
  7. 6.热点问题删除
  8. 7.热点问题上移
  9. 8.热点问题下移
  10. 9.热点问题保存
  11. 10.热点问题校验
  12. 11.热点问题列表

下图这一块是最麻烦的,调用的其他部分的组件,为了能复用,联调了很久。

之前封装的组件每一个动作是调接口的异步行为,此时改成同步的,最后保存一起提交。

那么在同步处理的时候,用到了很多数组的增删改,index索引值的变更。

下面,我首先总结一下数组处理的所有方法,再把在此处会用到的方法贴出来。


一.增加元素

1.push():push可接收任意数量的参数,把它们逐个添加至数组末尾,并且可以返回修改后数组的长度。

  1. var sports = ['soccer', 'baseball'];
  2. var total = sports.push('football', 'swimming');
  3.  
  4. console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
  5. console.log(total); // 4

2.unshift() :与push()类似,也可接收任意数量的参数,只不过是将参数逐个添加至数组最前面而已,同样返回新数组长度。

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

3.concat() :该方法与push()方法有点类似,同样是将元素添加至数组末尾,只不过这个数组已经不是原来的那个数组了,而是其副本,所以concat()操作数组后会返回一个新的数组。

特性:

    1. 不传参数,返回当前数组副本
    2. 传递非数组参数,这些参数就会被直接添加到结果数组的末尾
    3. 传递数组参数,将数组每一个元素,添加新的数组中
  1. const array1 = ['a', 'b', 'c'];
  2. const array2 = ['d', 'e', 'f'];
  3.  
  4. console.log(array1.concat(array2));
  5. // expected output: Array ["a", "b", "c", "d", "e", "f"]

4.splice(): 功能很强大,划重点

前面的三个方法都具有很大局限性,因为不是添加到数组前就是数组后,而splice()它非常灵活,它可以添加元素到数组的任意位置。

它除了可以添加元素之外还具有删除和替换元素的功能。

splice()可以向数组指定位置添加任意数量的元素。

需要传入至少3个参数:splice(a, b, c, d, ......)

    • 1、a 起始元素的位置
    • 2、b 要删除的元素个数,从起始元素开始算
    • 3、c后面的是要插入的元素,可以是数组

总结一下,原理就是,在规定的起始位置a,删除b个,如果后面需要塞进去新元素就加到cd...的位置,如果不加就是删除了,splice实质上是通过删除元素来实现插入、删除、替换的

4.1  splice 删除

写法

array.splice(index,n);

参数含义

index:数组中需要删除数据的起始位置;

n:需要删除的元素,数据的个数;

4.2   splice 插入

写法

array.splice(index,0,data1,data2,....);

参数

index:数组中需要插入数据的起始位置;

0:删除的个数为0;

data1,data2:需要插入的元素,用逗号隔开

4.3   splice 替换

写法

array.splice(index,n,data1,data2,......);

参数

index:需要替换的元素的起始位置;

n:需要替换的元素的个数,实质是删除;

data1,data2:需要插入元素,用逗号隔开;

二、删除元素

1.pop() :与push()方法配合使用可以构成后进先出的栈,该方法可从数组末尾删除最后一项并返回该项

  1. const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
  2.  
  3. console.log(plants.pop());
  4. // expected output: "tomato"
  5.  
  6. console.log(plants);
  7. // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
  8.  
  9. plants.pop();
  10.  
  11. console.log(plants);
  12. // expected output: Array ["broccoli", "cauliflower", "cabbage"]

  2.shift(): 与push()方法配合使用可以构成先进先出的队列,该方法可删除数组第一项并返回该项。

  1. const array1 = [1, 2, 3];
  2.  
  3. const firstElement = array1.shift();
  4.  
  5. console.log(array1);
  6. // expected output: Array [2, 3]
  7.  
  8. console.log(firstElement);
  9. // expected output: 1

  3.slice(): 该方法同concat()一样是返回一个新数组,不会影响原数组,只不过slice()是用来裁剪数组的,返回裁剪下来的数组。

slice()方法可以接受一或两个参数,

1、一个参数,返回从该参数指定位置开始到当前数组末尾的所有项。

2、两个参数,返回起始和结束位置之间的项,但不包括结束位置的项。

  1. const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
  2.  
  3. console.log(animals.slice(2));
  4. // expected output: Array ["camel", "duck", "elephant"]
  5.  
  6. console.log(animals.slice(2, 4));
  7. // expected output: Array ["camel", "duck"]
  8.  
  9. console.log(animals.slice(1, 5));
  10. // expected output: Array ["bison", "camel", "duck", "elephant"]

   4、splice(): 它除了可以添加元素之外还具有删除和替换元素的功能。 详细看以上例子

三、查找元素

indexOf() 和 lastIndexOf()

这两个方法都接收两个参数:

1、要查找的项

2、表示查找起点位置的索引。(可选的)

indexOf() 从数组的开头(位置0)开始向后查找。

lastIndexOf() 从数组的末尾开始向前查找。

两个方法,当找不到该元素时,都返回 -1

  1. var arr = [1,2,3,4,5,2];
  2.  
  3. var index = arr.indexOf(2);
  4.  
  5. console.log(index);  //
  6.  
  7. index = arr.indexOf(2, 0);
  8. console.log(index);  //
  9.  
  10. index = arr.indexOf(2, 2);
  11. console.log(index);  //
  12.  
  13. index = arr.indexOf(6);
  14. console.log(index);  // -1

其它方法:

1.join():该方法用来将数组转换为字符串,不改变原数组,返回转换后的字符串

  1. const elements = ['Fire', 'Air', 'Water'];
  2.  
  3. console.log(elements.join());
  4. // expected output: "Fire,Air,Water"
  5.  
  6. console.log(elements.join(''));
  7. // expected output: "FireAirWater"
  8.  
  9. console.log(elements.join('-'));
  10. // expected output: "Fire-Air-Water"

2.sort(): 按ascii码排序,改变原数组,返回排序后的数组

  1. const months = ['March', 'Jan', 'Feb', 'Dec'];
  2. months.sort();
  3. console.log(months);
  4. // expected output: Array ["Dec", "Feb", "Jan", "March"]
  5.  
  6. const array1 = [1, 30, 4, 21, 100000];
  7. array1.sort();
  8. console.log(array1);
  9. // expected output: Array [1, 100000, 21, 30, 4]

3.reverse() :用于颠倒数组中元素的顺序。返回的是颠倒后的数组,会改变原数组。

  1. const array1 = ['one', 'two', 'three'];
  2. console.log('array1:', array1);
  3. // expected output: "array1:" Array ["one", "two", "three"]
  4.  
  5. const reversed = array1.reverse();
  6. console.log('reversed:', reversed);
  7. // expected output: "reversed:" Array ["three", "two", "one"]
  8.  
  9. /* Careful: reverse is destructive. It also changes
  10. the original array */
  11. console.log('array1:', array1);
  12. // expected output: "array1:" Array ["three", "two", "one"]

4.filter():返回数组中满足条件的元素组成的新数组,原数组不变(筛选,过滤)

  1. const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
  2.  
  3. const result = words.filter(word => word.length > 6);
  4.  
  5. console.log(result);
  6. // expected output: Array ["exuberant", "destruction", "present"]

5.map() :map() 方法来根据需求格式化原数组,返回格式化后的数组。原数组不变。可以传入三个值,分别是(当前元素,索引index,map的原数组)

  1. var arr = [1,2,3,4,5,2];
  2. var arr2 = arr.map(function(current, index, array){
  3. console.log("当前元素current="+current + "索引index="+index +"数组array="+array)
  4. return "$"+current
  5. })
  6. console.log(arr) //[1, 2, 3, 4, 5, 2]
  7. console.log(arr2) //["$1", "$2", "$3", "$4", "$5", "$2"]

6.every() :对数组的每一项都运行给定的函数,若每一项都返回 ture,则返回 true($$)

  1. const isBelowThreshold = (currentValue) => currentValue < 40;
  2.  
  3. const array1 = [1, 30, 39, 29, 10, 13];
  4.  
  5. console.log(array1.every(isBelowThreshold));
  6. // expected output: true

7.some():对数组的每一项都运行给定的函数,若存在一项或多项返回 ture,否则返回 false(||)

  1. const array = [1, 2, 3, 4, 5];
  2.  
  3. // checks whether an element is even
  4. const even = (element) => element % 2 === 0;
  5.  
  6. console.log(array.some(even));
  7. // expected output: true

8.forEach() :遍历整个数组,不中断,可以传入三个值,分别是(当前元素,索引index,原数组)

  1. const array1 = ['a', 'b', 'c'];
  2.  
  3. array1.forEach(element => console.log(element));
  4.  
  5. // expected output: "a"
  6. // expected output: "b"
  7. // expected output: "c"

forEach和map很相似,很多地方用两个其中一种都行

相同点:

  1. 都是只能遍历数组
  2. 都有三个返回值(当前元素,索引index,原数组)
  3. 都是循环遍历数组每一项

区别是:

map,有返回值,可以return出来

forEach,没有返回值。forEach()返回值是undefined,不可以链式调用。

      没有办法终止或者跳出forEach()循环,除非抛出异常,所以想执行一个数组是否满足什么条件,返回布尔值,可以用一般的for循环实现,或者用Array.every()或者Array.some();

关于以上区别的笔试题

  1. ["1", "2", "3"].map(parseInt); //结果 [1, NaN, NaN] 
  2.  
  3. 如果想得到[1, 2,3]应该这么做
  1. function returnInt(element){
  2. return parseInt(element,10);
  3. }
  4.  
  5. ["1", "2", "3"].map(returnInt); 

这主要是因为 parseInt()默认有两个参数,第二个参数是进制数。当parsrInt没有传入参数的时候,而map()中的回调函数时候,会给它传三个参数,第二个参数就是索引,明显不正确,所以返回NaN了。

另,写map需要注意的点:

Arr
(Arr || []).map(item=>{})   这样写就会尽量避免报“Cannot read property 'map' of undefined”这个错误
 
定义object的时候尽量这样定义,避免后面报错

object
Const {a,b,c} = object || {}
Const {b,d} = a || {}

写到这里,发现这篇文章好长啊,已经写了一个小时了。不知道为什么博客园不能只用一种代码引入样式,两种弄的眼花缭乱,你们将就看吧。

下面贴一下实现最上面项目功能的store代码(技术栈react+mobx)

  1. // 新增一个空的热点问题
  2. @action addHotItem = (obj) => {
  3. const { handledHotTopicContext } = this.currentItem;
  4. const { list } = handledHotTopicContext
  5. this.currentItem = {
  6. ...this.currentItem,
  7. handledHotTopicContext: { ...handledHotTopicContext, list: [...list, obj], selectedItem: null }
  8. };
  9. }
  10.  
  11. // 保存一个热点问题(新增或修改)
  12. @action saveHotItem = (param, index) => {
  13. const { id } = param;
  14. const { handledHotTopicContext } = this.currentItem;
  15. const { list } = handledHotTopicContext
  16. // 编辑
  17. if (id !== undefined) {
  18. list.splice(id, 1, param);
  19. this.currentItem = {
  20. ...this.currentItem,
  21. handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
  22. };
          // 新增
  23. } else {
  24. const leg = list.length - 1
  25. const { name } = param
  26. const addObj = { id: leg, name: name }
  27. list.splice(leg, 1, addObj);
  28. // list.push(addObj)
  29. this.currentItem = {
  30. ...this.currentItem,
  31. handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
  32. };
  33. }
  34. }
  35.  
  36. // 删除一个热点问题
  37. @action delHotItem = (param) => {
  38. const { id } = param;
  39. const { handledHotTopicContext } = this.currentItem;
  40. const { list } = handledHotTopicContext
  41. list.splice(id, 1);
  42. this.currentItem = {
  43. ...this.currentItem,
  44. handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
  45. };
  46. }
  47.  
  48. // 上移下移一个热点问题
  49. @action moveHotItem = (item, key) => {
  50. let temp = null;
  51. const { id } = item;
  52. let index = 0;
  53. const { handledHotTopicContext } = this.currentItem;
  54. const { list } = handledHotTopicContext
  55. index = list.findIndex(ele => ele.id === item.id);
  56.  
  57. if (key === 'up') {
  58. temp = { ...list[index - 1] };
  59. list[index - 1] = { ...list[index] };
  60. list[index] = temp;
  61. this.currentItem = {
  62. ...this.currentItem,
  63. handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
  64. };
  65.  
  66. } else {
  67. temp = { ...list[index + 1] };
  68. list[index + 1] = { ...list[index] };
  69. list[index] = temp;
  70. this.currentItem = {
  71. ...this.currentItem,
  72. handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
  73. };
  74. }
  75. }

  

JS中对数组元素进行增、删、改、查的方法,以及其他方法的更多相关文章

  1. JS中对数组元素进行增删改移

    在js中对数组元素进行增删改移,简单总结了一下方法: 方法 说明 实例 push( ); 在原来数组中的元素最后面添加元素 arr.push("再见58"); unshift( ) ...

  2. js数组的管理[增,删,改,查]

    今天在设计表单的时候遇到对数组的一些处理的问题,比如说怎么创建一个数组,然后牵扯到数组的增删改查的方法.请看API FF: Firefox, N: Netscape, IE: Internet Exp ...

  3. 怎样从C#中打开数据库并进行 增 删 改 查 操作

    首先 在C#中引用数据库的操作! (因为我们用的是SQLserver数据库,所以是SqlClient) using System.Data.SqlClient; 1:要实现对数据库的操作,我们必须先登 ...

  4. JDBC中执行sql语句的 增 , 删 , 改 , 查 的方法

    executeQuery()  : 执行 SELECT 语句,它几乎是使用最多的 SQL 语句 executeUpdate() :   执行 INSERT.UPDATE 或 DELETE 语句以及 S ...

  5. 好用的SQL TVP~~独家赠送[增-删-改-查]的例子

    以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化.  本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...

  6. iOS FMDB的使用(增,删,改,查,sqlite存取图片)

    iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...

  7. iOS sqlite3 的基本使用(增 删 改 查)

    iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...

  8. django ajax增 删 改 查

    具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...

  9. ADO.NET 增 删 改 查

    ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...

随机推荐

  1. k8s的node节点,执行kubectl get XXX报错

    报错现象: [root@localhost ~]# kubectl get nodes The connection to the server localhost:8080 was refused ...

  2. 序列式容器————string

    目录 前言 1.构造函数 2.size() 3.length() 4.maxsize() 5.capacity() 6.reserve() 7.resize() 8.获取元素at() 9.字符串比较c ...

  3. dell笔记本 win10 下安装 ubuntu16.04 踩坑记录

    硬件配置情况: dell笔记本-灵越-5577 —— I5七代(带有集显),8G内存条DDR4,GTX1050,128G固态硬盘,1T机械硬盘. 固态硬盘划分为3部分,100GB给win10的C盘,1 ...

  4. Selenium 详解xpath定位

    xpath定位在业界被戏称为元素定位的"屠龙宝刀",宝刀在手,武林我有.现在我们就来详解xpath定位方法. 一.xpath通过元素属性定位 xpath可以通过元素的属性来定位,如 ...

  5. Hashtable 和 HashMap 的区别是:

    HashMap 是内部基于哈希表实现,该类继承AbstractMap,实现Map接口 Hashtable 线程安全的,而 HashMap 是线程不安全的 Properties 类 继承了 Hashta ...

  6. crontab定时调度shell脚本

    本人最近要用crontab做一个定时调度任务,调一个启动脚本去执行jar包,并给main方法传一个日期参数. Linux系统:CentOS7 输入: crontab -e 在里面编写: SHELL=/ ...

  7. 大数据笔记(二十三)——Scala语言基础

    一.Scala简介:一种多范式的编程语言 (*)面向对象 (*)函数式编程:Scala的最大特点 (*)基于JVM 二.Scala的运行环境 (1)命令行:REPL 进入: scala 退出::qui ...

  8. 【JQuery-02】事件绑定多次造成多次执行

    http://blog.csdn.net/always_littlesun/article/details/52594548

  9. value是列表的字典排序

    # -*- coding: utf-8 -*- def dict_test(): #构造Map并对其排序 attr_tul = list(['a','b','c']) one_tul = ,],[,] ...

  10. 分布式消息队列 Celery 的最佳实践

    目录 目录 不使用数据库作为 Broker 不要过分关注任务结果 实现优先级任务 应用 Worker 并发池的动态扩展 应用任务预取数 保持任务的幂等性 应用任务超时限制 善用任务工作流 合理应用 a ...