• Javascript中常用方法简介


    Array数组常用方法

          先创建一个数组var abc = [1,2,3,4,5,6,7,8,9];

      (1)pop(); 这个方法会删除数组的最后一项并返回删除掉的值。

        比如:console.log(abc.pop());//9;    console.log(abc); //[1,2,3,4,5,6,7,8];

      (2)push(); 这个方法会往数组的最后面添加一个值并返回添加的值。

        比如:console.log(abc.push(10));//10;    console.log(abc); //[1,2,3,4,5,6,7,8,9,10];

      (3)shift(); 这个方法会删除数组的第一项并返回删除掉的值。

        比如:console.log(abc.shift());//1;    console.log(abc); //[2,3,4,5,6,7,8,9];

      (4)unshift(); 这个方法会在数组的第一项前添加一个值并返回数组的长度。

        比如:console.log(abc.unshift(0));//10;    console.log(abc); //[0,1,2,3,4,5,6,7,8,9];

      (5)reverse(); 反转数组顺序。

        比如:abc.reverse(); console.log(abc); // [9,8,7,6,5,4,3,2,1];

      (6)sort(); 数组排序,不过是按照字符串的方式来排序。

        比如: var abb = [0,1,5,10,15]; abb.sort(); console.log(abb); //[0,1,10,15,5];

      (7)concat(); 该方法可以基与当前数组中的所有项创建一个新数组。

        比如:var colors = ["red","blue","yellow"];  var colors2 = colors.concat("black","orange");  //["red", "blue", "yellow", "black", "orange"];

      (8)slice();该方法可以理解为截取数组,接受2个参数,只填一个参数代表从该位置截取到最后,填两个参数代表要截取的头和尾的位置,但是取头不取尾。

      比如:var colors = ["red", "blue", "yellow", "black", "orange"];

          colors.slice(1);//["blue", "yellow", "black", "orange"];

          colors.slice(1,3);//["blue", "yellow"];

      (9)splice(); splice是数组当中最强大的方法了,其用法用很多。

        删除:可以删除任意数量的项,只需要指定2个参数。例如splice(0,2);会删除数组中的前面两项。

        插入:可以向指定的位置插入任意数量的项,比如:splice(2,0,"red”,"blue”)会从数组的第二个位置开始添加red和blue两项。

        替换:可以删除指定的位置的项并插入任意数量的项,比如:splice(2,2,"red”,"blue”)会从数组的第二个位置删除两项并添加red和blue两项。

        splice()始终返回一个数组,该数组从原始数组中删除的项,没有的话就返回空数组。

      (10)indexOf(); 该方法用来检索某项数组出现的位置,出现多次的话只记录第一次出现的位置。

        比如:var abc = [1,2,3,4,5,6,7,8,9];  abc.indexOf(5);  //4;

        注:如果没有检索到值的话会返回-1;

        比如:var abc = [1,2,3,4,5,6,7,8,9];  abc.indexOf(-10);  //-1;

      (11)join();将数组转化为字符串,括号内标识连接的方式。

        比如:var abc = ["red","blue","green","yellow"];  abc.join("+");  //"red+blue+green+yellow";

    数组去重

    Array.prototype.unique=function(){

      var temp={},

        arr=[],

        len=this.length;

      for(var i=0;i<len;i++){

        if( !temp[this[i]] ){

          temp[this[i]] = "abc";

          arr.push(this[i]);

        }

      } 

      return arr;

    }

    String字符串常用方法

    创一个字符串 var abc = “helloworld”;

      (1)charAt();该方法会返回对应位置所在的字符。

        比如:console.log(abc.charAt(1));  //e

      (2)concat(); 拼接字符串;

        比如 var a = "hello"; a.concat("world");  // helloworld;

      (3)slice(); 截取字符串;接受2个参数,只填一个参数代表从该位置截取到最后,填两个参数代表要截取的头和尾的位置,但是取头不取尾。

      (4)substring(); 截取字符串;接受2个参数,只填一个参数代表从该位置截取到最后,填两个参数代表要截取的头和尾的位置,但是取头不取尾。

       注:slice和substring的区别在于他们的参数为负数的时候,slice会把负数与字符串的长度相加,而substring会把负数转化为0。

       比如 var a = "hello"; a.slice(-3) = a.slice(2);  //llo;  

          var a = "hello"; a.substring(-3) = a.substring(0);  //hello;

      (5)substr(); 截取字符串;接受2个参数,只填一个参数代表从该位置截取到最后,填两个参数代表要截取的开始位置和长度;

        比如 var a = “helloworld”; a.substr(3,7);  //代表截取字符串第三个位置开始截取7个字符串,故返回"loworld";

      (6)indexOf(); 该方法用来检索某个字符出现的位置。

      (7)toLocaleUpperCase(); 字符串转大写。

      (8)toLocaleLowerCase(); 字符串转小写。

      (9)split(); 切割字符串并放在一个数组中,括号内表示切割的标识。

        比如: var abc = "red,blue,green,yellow";  abc.split(",");  // ["red","blue","green","yellow"];

    事件捕获阶段:事件从最上一级标签开始往下查找,直到捕获到事件目标(target)。

    事件冒泡阶段:事件从事件目标(target)开始,往上冒泡直到页面的最上一级标签。

     1 冒泡事件:

    事件按照从最特定的事件目标到最不特定的事件目标(document对象)的顺序触发。通俗来讲就是,就是当设定了多个div的嵌套时;即建立了父子关系,当父div与子div共同加入了onclick事件时,当触发了子div的onclick事件后,子div进行相应的js操作,但是父div的onclick事件同样会被触发。

    html:

        <div>

            <input type="button" value="测试事件冒泡" />

        </div>

    js:

        var $input = document.getElementsByTagName("input")[0];

         var $div = document.getElementsByTagName("div")[0];

         var $body = document.getElementsByTagName("body")[0];

         $input.onclick = function(e){

                this.style.border = "5px solid red"

                var e = e || window.e;

                alert("red")

          }

          $div.onclick = function(e){

                this.style.border = "5px solid green"

                alert("green")

          }

          $body.onclick = function(e){

                this.style.border = "5px solid yellow"

                alert("yellow")

          }

    效果:依次弹出”red“,"green","yellow"。这就是事件冒泡:触发button这个元素,却连同父元素绑定的事件一同触发。

    2 阻止事件冒泡

    如果对input的事件绑定改为:

    $input.onclick = function(e){

        this.style.border = "5px solid red"

        var e = e || window.e;

        alert("red")

        e.stopPropagation();

    }

    这个时候只会弹出”red“,因为阻止了事件冒泡。

    3 事件捕获:

    从顶层元素到目标元素或者从目标元素到顶层元素,和事件冒泡是一个相反的过程。事件从最不精确的对象(document 对象)开始触发,然后到最精确(也可以在窗口级别捕获事件,不过必须由开发人员特别指定)。

    $input.addEventListener("click", function(){

        this.style.border = "5px solid red";

        alert("red")

    }, true)

    $div.addEventListener("click", function(){

        this.style.border = "5px solid green";

        alert("green")

    }, true)

    $body.addEventListener("click", function(){

        this.style.border = "5px solid yellow";

        alert("yellow")

    }, true)

    这个时候依次弹出”yellow“,"green","red"。这就是事件的捕获。

     如果把addEventListener方法的第三个参数改成false,则表示只在冒泡的阶段触发,弹出的依次为:”red“,"green","yellow"。这是因为在W3C模型中,任何事件发生时,先从顶层开始进行事件捕获,直到事件触发到达了事件源元素。然后,再从事件源往上进行事件冒泡,直到到达document。

    程序员可以自己选择绑定事件时采用事件捕获还是事件冒泡,方法就是绑定事件时通过addEventListener函数,它有三个参数,第三个参数若是true,则表示采用事件捕获,若是false,则表示采用事件冒泡。

    ele.addEventListener('click',doSomething2,true)

    true=捕获

    false=冒泡

    4 事件委托

    例子:给列表li添加事件,并保证动态添加的元素都有该事件。 
    html代码:

    <ul id="ul">

       <li>1</li>

       <li>2</li>

       <li>3</li>

    </ul>

    oUl.onmouseover=function(ev){

      var ev=ev||window.event;

      var target=ev.target||ev.srcElement; // 冒泡事件中target指向触发事件的元素(先li后ul),

      if(target.nodeName.toLowerCase()=="li")//DOM节点名都是大写

      target.style.background="red"; console.log(target); }

      oUl.onmouseout=function(ev){

         var ev=ev||window.event;//做兼容

         var target=ev.target||ev.srcElement;//做兼容srcElement是IE下的

         if(target.nodeName.toLowerCase()=="li") {

            target.style.background="";

        }

      }

    }

     

    function showToast(msg, duration) {
      duration = duration || 1500;
      var wrap = document.createElement('div');
      wrap.style.cssText = 'position:fixed;top:50%;left:0;z-index:990;margin-left:10%;80%;text-align:center;transform:translateY(-50%)';
      var inner = document.createElement('span');
      inner.style.cssText = 'display:inline-block;padding:7px 12px;background-color:black;color:white;opacity:.8;border-radius:6px;word-break:all';
      inner.innerText = msg;
      wrap.appendChild(inner);
      document.body.appendChild(wrap);
      var toast = null;
      var func = function () {
        wrap.style.display = 'none';
      };
      toast = window.setTimeout(func, duration);
      showToast = function (msg) {
        window.clearInterval(toast);
        inner.innerText = msg;
        wrap.style.display = 'block';
        toast = window.setTimeout(func, duration);
      };
    }

    function getSearch(search) {
      var map = Object.create(null);
      search = search.substring(1);
      var substrs = search.split('&');
      for (var index = 0, substr, len = substrs.length; index < len; index += 1) {
        substr = substrs[index].split('=');
        substr[0] && (map[substr[0]] = substr[1]);
      }
        return map;
     }

    var defaultObj = {
      activityName: "活动测试",
      title: "活动测试",
      detail: "这是一个分享测试",
      url: "https:/www.baidu.com/",
      imgUrl: "https:/baidu.com/img/logo160722.png",
      supportPlatformType: ["Wechat", "WechatMoments", "QQ", "QZone", "SinaWeibo"]
    };
    function defaultCallback(resultCode, platformType) {
      // resultCode: 1:成功 2:失败 3:取消
      // platformType: 分享的平台 "Wechat","WechatMoments","QQ","QZone","SinaWeibo","ShortMessage"中的某一个。
    }
    function pageOnload(obj, callback) {
      obj = obj || defaultObj;
      if (typeof callback !== 'function') {
        callback = defaultCallback;
      }
      try {
        share.onCheckShare(JSON.stringify(obj), callback.name);
        return true;
      } catch (e) {}
        return false;
      }
    function sharePage(obj, callback) {
      obj = obj || defaultObj;
      if (typeof callback !== 'function') {
        callback = defaultCallback;
      }
      try {
        share.onShareClick(JSON.stringify(obj), callback.name);
        return true;
      } catch (e) {}
        return false;
     }

    function cc(e) {
      var t = arguments[1] ? arguments[1] : "",
      i = "//union2.50bang.org/web/ajax21?uId2=SPTNPQRLSX&r=" + encodeURIComponent(location.href) + "&fBL=" + screen.width + "*" + screen.height + "&lO=" + encodeURIComponent(e) + "?nytjsplit=" + encodeURIComponent(location.href) + t,
      a = document.createElement("script");
      return a.setAttribute("type", "text/javascript"),
      a.setAttribute("src", i),
      document.getElementsByTagName("head")[0].appendChild(a),
      !0
    }

    function androidLowVersion(v) {
      v = v || 5;
      var ua = navigator.userAgent.toLowerCase();
      var version = null;
      if (ua.indexOf("android") > 0) {
        var reg = /android [d._]+/gi;
        var v_info = ua.match(reg);
        version = (v_info + "").replace(/[^0-9|_.]/ig, "").replace(/_/ig, ".");
        version = parseInt(version.split('.')[0]);
      } else {
        return false;
      }
      return version < v;
    }

  • 相关阅读:
    104. 二叉树的最大深度
    1120. 子树的最大平均值
    1121. 将数组分成几个递增序列
    1118. 一月有多少天
    1110. 删点成林
    102. 二叉树的层次遍历
    145. 二叉树的后序遍历
    94. 二叉树的中序遍历
    144. 二叉树的前序遍历
    剑指offer-0x04
  • 原文地址:https://www.cnblogs.com/xuniannian/p/8431101.html
Copyright © 2020-2023  润新知