数组

扩展

  1. var a=[1,2]
  2. var b = [...a,3]
  3. console.log(b) //1,2,3

map,reduce,filter,forEach

都不会改变原数组

map 映射

  1. let arr = [1,2,3,43,5464,46,12]
  2. let arr2 = arr.map(item=>item>=60)
  3. console.log(arr2)
  4. // [ false, false, false, false, true, false, false ]

filter 过滤

  1. let arr = [1,2,3,43,5464,46,12]
  2. let arr2 = arr.filter(item=>item%2)
  3. console.log(arr2) //[ 1, 3, 43 ]

forEach 遍历

  1. let arr = [1,2,3,43,5464,46,12]
  2. let sum=0
  3. arr.forEach(item=>{
  4. sum+=item
  5. })
  6. console.log(sum) //5571

reduce 汇总

  1. let arr = [1,2,3,43,5464,46,12]
  2. let sum = arr.reduce((tmp,item,index)=>{
  3. return tmp+item
  4. })
  5. console.log(sum) //5571

合并数组内两个对象里相同属性的值为数组

  1. console.time()
  2. //原数据
  3. var list = [{
  4. brand: 'Hisense1',
  5. name: 'C Series',
  6. type: '多联机和新风机通用室外机',
  7. photo: '',
  8. minRatio: 0.5,
  9. maxRatio: 1.3,
  10. alarmMaxRatio: 0,
  11. isOnmarket: true,
  12. isDefault: false,
  13. DWGFile: '',
  14. pictureFile: '',
  15. remarks: '',
  16. id: 'b53d408d-c4f9-4751-86a0-37751c48c6ad',
  17. },
  18. {
  19. brand: 'Hisense2',
  20. name: 'C Series',
  21. type: '多联机和新风机通用室外机',
  22. photo: '',
  23. minRatio: 0.5,
  24. maxRatio: 1.3,
  25. alarmMaxRatio: 0,
  26. isOnmarket: true,
  27. isDefault: false,
  28. DWGFile: '',
  29. pictureFile: '',
  30. remarks: '',
  31. id: 'b53d408d-c4f9-4751-86a0-37751c48c6ad',
  32. },
  33. ]
  34. const mergedObject = list.reduce(
  35. // target: 目录对象, item: 当前遍历到的元素(对象)
  36. (target, item) => ({
  37. // 先将目录对象已经取得的值全部赋予新目录对象
  38. ...target,
  39. // 拿到 item 的 key 列表,并且通过该列表去创建一个新的对象
  40. ...Object.keys(item).reduce(
  41. // 新的对象,以及 item 中的一个 key
  42. (object, key) => ({
  43. // 新对象先把已有的属性全部加上
  44. ...object,
  45. // 设定当前的 key 对应的值
  46. [key]: Array.isArray(target[key]) ?
  47. target[key].concat(item[key]) // 如果当前的 key 在 target[key] 中是数组,则表示已经存在超过两个具有该 key 的对象了,所以直接将新值 concat 进去即可
  48. : // : target[key] // 否则的话,判断 target[key] 上面是否已经存在该值了
  49. target.hasOwnProperty(key) // 更新一下,需要拿 `hasOwnProperty` 判断,否则如果值为 0, false, undefined 等,都会被判错
  50. ?
  51. [target[key], item[key]] // 如果存在了该值,则将该值变成一个数组(因为已经有两个了)
  52. :
  53. item[key], // 否则的话,就把当前这个值赋值给 target
  54. }), {}
  55. ),
  56. }), {}
  57. )
  58. console.log(mergedObject)
  59. console.timeEnd()
  60. // 0.08203125 ms

from

  1. let str = '123123'
  2. Array.from(str).forEach(item=>console.log(item)) //123123
  3. Array.prototype.slice.call(str).forEach(item=>console.log(item))
  4. //123123
  5. [...str].forEach(item=>console.log(item))

json

简写
省略function

  1. let a = 1
  2. let b = 2
  3. let json_1 = {a,b}
  4. console.log(json_1) //{ a: 1, b: 2 }
  5. //对象里函数简写
  6. let json_2 = {
  7. a : 1,
  8. b : 2,
  9. show(){
  10. console.log(a+b)
  11. }
  12. }
  13. json_2.show() //3