标签 javascript 下的文章

JavaScript使用Websocket


<script>
  function WebSocketTest() {
    if ("WebSocket" in window) {
      alert("您的浏览器支持 WebSocket!");

      // 打开一个 web socket
      var ws = new WebSocket("ws://localhost:8080/");

      ws.onopen = function () {
        // Web Socket 已连接上,使用 send() 方法发送数据
        ws.send(`{"Data":"sadddddddddd"}`);
      };

      ws.onmessage = function (evt) {
        var received_msg = evt.data;
        console.log(received_msg)
      };

      ws.onclose = function () {
        // 关闭 websocket
        alert("连接已关闭...");
      };
      
    }else {
      // 浏览器不支持 WebSocket
      alert("您的浏览器不支持 WebSocket!");
    }
  }

  WebSocketTest()
</script>

webScoket测试工具

https://www.52bd.net/usr/uploads/2020/04/751993603.html

2020-04-28T07:47:20.png
WebSocketTest.html


js怎么对数据分组,类似group by


list = [
  {"name": "John", "Average": 15, "High": 10, "DtmStamp": 1358226000000},
  {"name": "Jane", "Average": 16, "High": 92, "DtmStamp": 1358226000000},
  {"name": "Jane", "Average": 17, "High": 45, "DtmStamp": 1358226000000},
  {"name": "John", "Average": 18, "High": 87, "DtmStamp": 1358226000000},
  {"name": "Jane", "Average": 15, "High": 10, "DtmStamp": 1358226060000},
  {"name": "John", "Average": 16, "High": 87, "DtmStamp": 1358226060000},
  {"name": "John", "Average": 17, "High": 45, "DtmStamp": 1358226060000},
  {"name": "Jane", "Average": 18, "High": 92, "DtmStamp": 1358226060000}
];

ngOnInit() {
  const sorted = this.groupBy(this.list, function (item) {
    return [item.name];
  });
  console.log(sorted);

}

groupBy(array, f) {
  //debugger;
  const groups = {};
  array.forEach(function (o) {
    const group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function (group) {
    return groups[group];
  });
}

ngOnInit()

具体实现思路:

  1. 函数groupBy有两个形参,一为对象数组,二为匿名函数(该函数功能:返回对象的某个指定属性的属性值并存放在数组中);
  2. groupBy函数内,先创建一个空对象;
  3. 然后forEach遍历对象数组,遍历时要执行的函数中只有一个形参o(数组中的每个元素);
  4. 由于下面函数调用是想用name来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的name属性对应的属性值并放入数组中:["John"],然后再将属性值转换为json字符串:'["John"]';
  5. groups[group] = groups[group] || [],在js中对象也是关联数组,因此这里相当于做了两件事,一是把group作为groups的key,二是将对应的value初始化,第一次执行为空数组,循环执行时找到相同的name时保持不变;
  6. groups[group].push( o ),这句相当于把list中每个对象压入数组中作为value;
  7. 最后,Object.keys(groups)是取出groups对象中的所有key,然后遍历一个个key组成的新数组,返回分好了组的二维数组


ant design pro 怎么使用原生高德地图插件,怎么引入外部js文件使用


index.less:

.sssssssss{
  height: 500px;
  width: 100%;
}

index.tsx:

import React, { useState, useEffect } from 'react';
import MapComponent from './gddt'

export default () => {
  const [loading, setLoading] = useState<boolean>(true);
  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000);
  }, []);

  return (
    <>
    <MapComponent />
    </>
  );
};

gddt.tsx代码:

import React from 'react';
import styles from './index.less';


// tslint:disable-next-line:max-classes-per-file
class MapComponent extends React.Component {

    public componentDidMount() {
        window.onLoad = function () {
            var map = new AMap.Map('map');
        }
        var url = 'https://webapi.amap.com/maps?v=1.4.15&key=你申请的key&callback=onLoad';
        var jsapi = document.createElement('script');
        jsapi.charset = 'utf-8';
        jsapi.src = url;
        document.head.appendChild(jsapi);
    }
    public render() {
        return (
            <>   //这里要加样式 高 宽
                <div id="map" className={styles.sssssssss} ></div>
            </>
        )
    }
}

export default MapComponent;

效果图:
QQ图片20200323161027.png


ant design pro 怎么使用websocket 推送消息


namespace: 'global',

state: {
  collapsed: false,
  notices: [],
},

reducers: {
     saveNoticesWebsock(state, { payload }): GlobalModelState {//此处可以根据自己的业务写
      let dd=[...payload,...state.notices];
      console.log(dd,"saveNoticesWebsock")
      return {
        collapsed: false,
        ...state,
        notices: dd,
      };
    },
},

subscriptions: {
    setup({ dispatch,history }): void {
      
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      history.listen(({ pathname, search }): void => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
        if (!pathname.indexOf('/welcome')) {
          const ws = new WebSocket('ws://127.0.0.1:1234/websocket');
          ws.onmessage = function(msg) { 
            console.log('接收服务端发过来的消息', msg); 
            // result += msg.data + '\n'; 
            dispatch({
              type: 'saveNoticesWebsock', 
              payload: JSON.parse(msg.data),
            });
          }; 
          ws.onclose = function (e) {
              console.log('ws 连接关闭了');
          }
        }
      });
    }
  },

js(es6) generator函数


<script>
    function * gen(){
        yield 'welcome';
        yield 'to';
        yield '吾爱博客';
    }

    let g1 = gen();
    
    // v1 = g1.next()
    // console.log(v1.value,v1.done)
    // v1 = g1.next()
    // console.log(v1.value,v1.done)
    // v1 = g1.next()
    // console.log(v1.value,v1.done)
    // v1 = g1.next()
    // console.log(v1.value,v1.done)

    for (const iterator of g1) {
        console.log(iterator)
    }

    console.log(...gen())
</script>

输出

welcome
to
吾爱博客
welcome to 吾爱博客

js(es6) Symbol基本类型


1、Symbol()不能New
2、Symbol()返回是一个唯一值,传说中用来做key的,定义一些唯一的或者私有的东西
3、Symbol是基本类型
4、for in 不能循环出来(私有的)

<script>
    let k = Symbol("Strive")
    let kk = Symbol("Strive")
    let json = {
        a:'apple',
        b:'banana',
        [k]:'aaa',
        [kk]:'bbb'
    }
    
    console.log(json[k],json[kk])

    //[k]不会循环出来
    for (const key in json) {
        if (json.hasOwnProperty(key)) {
            const element = json[key];
            console.log(key,element)
        }
    }
</script>

输出:

aaa bbb
a apple
b banana

js(es6)类的继承extends和super的使用


<script>
    //父类
    class Person{
        constructor(name){
            this.name = name
        }

        showName(){
            console.log(`父类名字:${this.name}`)
        }

    }
    //子类
    class Student extends Person{
        constructor(name,skill){
            super(name)
            this.skill = skill
        }
        showName(){
            super.showName();//父级的方法执行
            console.log(`子类名字:${this.name}`)
        }
        showSkill(){
            return `技能:${this.skill}`
        }
    }

    let s = new Student("吾爱博客","逃学")
    console.log(s.skill,s.name)
    s.showName()

</script>

js(es6) 类class constructor、static、set、get


<script>
    let funcName = 'test'
    class Student{
        constructor(name,age){
            this.name = name
            this.age = age
        }
        static StudentMsg(){
            console.log(`静态方法执行~~~`)
        }
        showStudentName(){
            console.log(`学生名字:${this.name}`)
        }
        showStudentAge(){
            console.log(`学生年龄:${this.age}`)
        }
        [funcName](){
            console.log(`这是一个动态方法名${funcName}`)
        }

        set setName(name){
            this.name = name
            console.log(`set Name:${this.name}`)
        }

        get getName(){
            console.log(`get Name:${this.name}`)
        }

    }

    let s = new Student("吾爱",18)
    Student.StudentMsg()
    s.showStudentName()
    s.showStudentAge()
    s[funcName]()
    s.test()
    
    s.setName = `吾爱博客`
    s.getName
</script>

js(es6)模块化



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <p>模块化需要服务器环境</p>
    <p>import 可以是相对路径,也可以是绝对路径。</p>
    <p>import 无论重复多少次 ,模块只会导入一次。</p>
    <p>import 提升,会优先执行。</p>
    <p>export 导出内容,如果里面有更改,外面也会改动。</p>
    <p>import() 动态引入,返回值是 promise对象</p>
    <p>模块化需要服务器环境</p>
</head>
<body>
    
</body>
</html>

<script type="module">
    import {a,b,xx as x,yy as y} from  './modules/m.js'
    console.log(a,b,x,y)
</script>

<script type="module">
    import * as all from  './modules/m.js'
    console.log(all)
</script>

<script type="module">
    import a  from  './modules/m.js'
    console.log(a)
</script>

<script type="module">
    let a = 1;
    let urlStr = './modules/m2.js'
    if(a == 1){
        import(urlStr).then(res=>{
            console.log(res.p)
        })
    }
</script>


<script type="module">
    Promise.all([
        import('./modules/j1.js'),
        import('./modules/j2.js')
    ]).then(([mod1,mod2])=>{
        console.log(mod1,mod2)
    })
    console.log(p)
</script>

js(es6) promise异步


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    let a = 1

    let promise = new Promise(function(resolve,reject){
        if(a == 10){
            resolve('成功')
        }else{
            reject('失败鸟')
        }
    })

    //promise.then(success,fail);
    promise.then(x => {
        console.log(x);
    },err => {
        console.log(err)
    })

    promise.catch(err =>{ //发送错误,别名 
        console.log(err)
    })

    //成功的简写方法
    let p1 = Promise.resolve('aaa');
    p1.then(res => {
        console.log(res)
    })

    //失败的简写方法
    let p2 = Promise.reject('aaa');
    p2.then(res => {
        console.log(res)
    }).catch(err => {
        console.log("错误了")
    })

    
    
    let p3 = Promise.resolve('aaa');
    p3.then(res => {
        console.log(res)
    })
    let p4 = Promise.resolve('bbb');
    p4.then(res => {
        console.log(res)
    })
    let p5 = Promise.resolve('ccc');
    p5.then(res => {
        console.log(res)
    })
    //必须保证 promise对象都是resolve状态(成功状态)
    Promise.all([p3,p4,p5]).then(res=>{
        let [res1,res2,res3] = res
        console.log(res1,res2,res3)
    })

    // race对象只要有有一个resolve状态(成功状态)
    Promise.race([p3,p4,p5]).then(res=>{
        let [res1,res2,res3] = res
        console.log(res1,res2,res3)
    })


</script>