练习

//实现指定多少时间后执行callback

const wait = (delay,callback) => {
    let p = new Promise((res,rej)=>{
        setTimeout(()=>{
            res(callback)
        },delay)
    }).then((callback)=>{
        callback();
    })
    return p
}
async function helloAsync(){
   await wait(3000,()=>console.log("something important"));
}
//helloAsync();

const result = wait(3000,()=>console.log("something important"));
console.log(result)//"something important"

 

//累加数组每一项

((arr) => {
    let tot1 = 0;
    arr.map((item)=>tot1 += item);
    console.log(tot1)

    let tot2 = arr.reduce((prve,next)=>{
        return prve+next
    },0)
    console.log(tot2)

    let tot3 = 0;
    arr.filter(item=>tot3 += item)
    console.log(tot3)

    let tot4 = eval(arr.join('+'))
    console.log(tot4)

})([1,2,3,.5,100])
//106.5     
//[1,2,3,.5,'100']只有tot4转数字相加,其他三个都是字符串拼接  

 

//数组每一项的平方值

((arr) => {

    let tot2 = arr.map((item)=>{
        //console.log(item)
        return item * item
    },0)
    console.log(tot2)

})([1,2,3,4,5,6,7,8,9,10])

 

//查找字符串出现次数

function findSameStrs(s) {
 if(typeof s !== "string") return '';
 var str = s;
  //下面对乱的字符排序,如果题目要求”连续出现”最多字符的话,不用写
  str = s.split('').sort((a,b)=>a.localeCompare(b)).join('');
    console.log(str)
  var reg = /(\w)\1+/g;

  var arr = str.match(reg);//捕获匹配的字符
    console.log(arr)
  if(arr){
  // 将正则匹配到的结果继续按照字符串的长度排序(从大到小)
    arr.sort((a,b)=>b.length - a.length);

    console.log("出现次数最多的字符是:" + arr[0][0] + "出现:" + arr[0].length + "次")
  }else{
  // 如果正则没有匹配到的,则表示该字符串没有重复出现的字符,默认打印字符串第一位
    console.log("出现次数最多的字符是:" + s[0], "出现: 1次")
  }
}
findSameStrs('aabbcccddeeeeas;dfjas;f')

//;;aaaabbcccdddeeeeffjss
//["aaaa", "bb", "ccc", "ddd", "eeee", "ff", "ss"]
//出现次数最多的字符是:a出现:4次

 

多行展开收起自动隐藏(css)

.wrapper {
  display: flex;
  margin: 50px auto;
  width: 800px;
  overflow: hidden;
  border-radius: 8px;
  padding: 15px ;
border:1px solid #ff9900;
}
.text {
  font-size: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: justify;
  position: relative;
  line-height: 1.5;
  max-height: 4.5em;
  transition: 3s max-height;
}
.text::before {
  content: '';
  height: calc(100% - 26px);
  float: right;
}
.text::after {
  content: '';
  width: 999vw;
  height: 999vw;
  position: absolute;

    margin-left: -100px;
}
.btn{
  position: relative;
  float: right;
  clear: both;
  margin-left: 20px;
  font-size: 16px;
  padding: 0 8px;
  background: #3F51B5;
  line-height: 24px;
  border-radius: 4px;
  color:  #fff;
  cursor: pointer;
}
.btn::after{
  content:'展开'
}
.exp{
  display: none;
}
.exp:checked+.text{
  max-height: none;
}
.exp:checked+.text::after{
  visibility: hidden;
}
.exp:checked+.text .btn::before{
  visibility: hidden;
}
.exp:checked+.text .btn::after{
  content:'收起'
}
.btn::before{
  content: '...';
  position: absolute;
  left: -5px;
  color: #333;
  transform: translateX(-100%)
}
<div class="wrapper">
    <input id="exp1" class="exp"  type="checkbox">
    <div class="text">
        <label class="btn" for="exp1"></label>
        浮动元素是如何定位的正如我们前面提到的那样,当一个元素浮动之后,它会被移出正常的文档流,然后向左或者向右平移,一直平移直到碰到了所处的容器的边框,或者碰到另外一个浮动的元素。在下面的图片中,有三个红色的正方形。其中有两个向左浮动,一个向右浮动。要注意到第二个向左浮动的正方形被放在第一个向左浮动的正方形的右边。如果还有更多的正方形这样浮动,它们会继续向右堆放,直到填满容器一整行,之后换行至下一行。
    </div>
</div>

 

快速输出一百个数

[...Array(100).keys()]
[...Array(100).keys()].join()
[...Array(101).keys()].join().slice(2)

10以内随机整数

function ssa(){
    var num = Math.round(Math.random()*10)
    console.log(num)
}
ssa() 

 

执行函数,每次都输出累加1

方法1
const counter = (function() { let i = 0 return () => { return ++i } }()) 方法2 const counter = () => { // const str = window.str || '' // window.str = str + ',' // return str.split(',').length if(typeof window.str != 'undefined'){ window.str += '1' }else{ window.str = '1' } return window.str.length } console.log(counter())//1 console.log(counter())//2 console.log(counter())//3 console.log(counter())//4

 

textarea获取选取的文本

<textarea rows="4" cols="5" id="tete" onselect="btnnFn()">234567</textarea>

let tete = document.getElementById("tete")
function btnnFn(){
    tete.focus()
    let start = tete.selectionStart;
    let end = tete.selectionEnd;
    let ss = tete.value.substring(start,end)
    console.log(ss)
}
tete.setSelectionRange(1,4)//通过索引可以自动选取文本

 

使用addEventListener监听 keydown,keyup,keypress 有问题

keypress   不能监听功能键ctrl、shift、退格等,可以监听enter || event.charCode等于event.keyCode的值a-97,b-98,c-99,这个不准

keydown和keyup   能监听功能键ctrl、shift、退格等,可以监听enter || event.charCode的值全是0,event.keyCode的值a-65,b-66,c-67

但使用box.addEventListener("keydown",(e)=>{})监听时,input框里已经键入值了,不能起到阻止输入的作用

//使用onkeydown
box.onkeydown = (e)=>{ if((!/\d/.test(String.fromCharCode(e.keyCode)) || e.keyCode==17) && e.keyCode!==8){ e.preventDefault() } }

 

创建对象设置属性

var obj = {}
Object.defineProperty(obj,'a',{
    value:12,
    writable:false,
    configurable:false
})

 

slot插槽

let ary = ['red','green','blue']

for(let color of ary){
    console.log(document)
    let divElement = document.createElement('div')
    divElement.innerText = `
        1231 ${color}
    `

    document.body.appendChild(divElement)
    divElement.attachShadow({mode:"open"}).innerHTML = `
        <p><slot></slot></p>
        <style>
        p{
            color:${color}
        }
        </style>
    `
}

 

动态加载模板

<body>
    <template id="foo">
        <script>console.log(123123)</script>
        <!-- <script src="http://www.h5al.cn/js/vue.js"></script> -->
    </template>
    <div id="box"></div>
</body>
<script>

let box = document.querySelector("#box")
let foo = document.querySelector("#foo")
let temp = foo.content

setTimeout(()=>{
box.appendChild(temp)
},2000)
</script>

 

委托控件对象——动态创建按钮JQ

var Widget = {
    init: function(width,height){
        this.width = width || 50;
        this.height = height || 50;
        this.$elem = null;
    },
    insert: function($where){
        if(this.$elem){
            this.$elem.css({
                width: this.width + 'px',
                height: this.height + 'px'
            }).appendTo($where)
        }
    }
}

var Button = Object.create(Widget);

Button.setup = function(width,height,label){
    this.init(width,height);
    this.label = label || 'Default';
    this.$elem = $("<button>").text(this.label);
}

Button.build = function($where){
    this.insert($where);
    this.$elem.click(this.onClick.bind(this));
}
//按钮根据传进来的label不同可以做不同的事
Button.onClick = function(evt){
    console.log("Button '" + this.label + "' clicked!");
}

$(function(){
    var $body = $(document.body)
    var btn1 = Object.create(Button)
    btn1.setup(150,40,"Hello");
    var btn2 = Object.create(Button)
    btn2.setup(150,40,"World")

    btn1.build($body)
    btn2.build($body)
})

 

//保留前四位后四位

var str = '6230201090136410'
var val = ''
if(str.length > 8){
    val = str.replace(/^(\w{4})(\w*)(\w{4})$/g,function(){
        return arguments[1] + arguments[2].replace(/\w/g,'*') + arguments[3]
    })
}else{
    val = str
}
var ss = str.replace(/^(\w{4})\w+(\w{4})$/,'$1******$2')

 

//手机号码中间四位****

var ary = '13300009999'.split('')
ary.splice(3,4,'****')
var str = ary.join('')
console.log(str)

 

//字符串原位反转

var str = 'asdf qwer zxcv 1234'
str.split(' ').reverse().join(' ').split('').reverse().join('')
"fdsa rewq vcxz 4321"
str.split('').reverse().join('')
"4321 vcxz rewq fdsa"
str.split(' ').reverse().join(' ')
"1234 zxcv qwer asdf"

 

//正则两个小分组替换

var str = 'a&nbsp;sdlspan-span-asspandj;&nbsp;2&nbsp;3'
var res = str.replace(/(span)|(&nbsp;)/g,function(){
    if(arguments[1]){
        return 'div'
    }
    if(arguments[2]){
        return '123'
    }
});
console.log(res)

 

//阿拉伯数字转中文数字

function NoToChinese(num){
    if(!/^\d*(\.\d*)?$/.test(num)){
        alert("Number is wrong!");
        return "Number is wrong!";
    }
    var AA = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");
    var BB = new Array("","拾","佰","仟","万","亿","点","");
    var a = ("" + num).replace(/(^0*)/g,"").split("."),
        k = 0,
        re = "";
    for(var i=a[0].length-1;i>=0;i--){
        switch(k){
            case 0:
                re = BB[7]+re;
                break;
            case 4:
                if(!new RegExp("0{4}\\d{" + (a[0].length-i-1) + "}$").test(a[0])){
                    re = BB[4]+re;
                }
                break;
            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k=0;
                break;
        }
        if(k%4 == 2 && a[0].charAt(i+2) != 0 && a[0].charAt(i+1) == 0){
            re = AA[0] + re;
        }
        if(a[0].charAt(i) != 0){
            re = AA[a[0].charAt(i)] + BB[k%4] + re;
        }
        k++;
    }
    if(a.length>1){
        //加上小数部分(如果有小数部分)
        re += BB[6];
        for(var i=0;i<a[1].length;i++){
            re += AA[a[1].charAt(i)]
        }
    }
    return re;
}
console.log(NoToChinese(189233.389))

 

//比较两个对象

function isObjectEqual(obj1, obj2) {
  const obj1Keys = Object.keys(obj1);
  const obj2Keys = Object.keys(obj2);

  if (obj1Keys.length !== obj2Keys.length) {
    return false;
  }

  for (let key of obj1Keys) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
}

const obj1 = { a: 1, b: "hello" };
const obj2 = { a: 1, b: "world" };
const obj3 = { a: 1, b: "hello" };

console.log(isObjectEqual(obj1, obj2)); // false
console.log(isObjectEqual(obj1, obj3)); // true

 

//时间格式化

let switchCase = (obj) => (key) => obj[key] ? obj[key] : obj.default;
let res = '20210426141823'.split('').reduce((prev,next,index)=>{
    next += switchCase({
        '3': '年',
        '5': '月',
        '7': '日 ',
        '9': ':',
        '11': ':',
        'default': ''
    })(index);
    return prev + next
},'')

let ase = function (obj){
    return function (key){
        return obj[key]
    }
}
let obj = {'1':'123','2':'12'}
console.log(ase(obj)('2'))

 

posted @ 2021-10-27 09:23  石头记1  阅读(39)  评论(0编辑  收藏  举报