• JavaScript类型操作以及一些规范


    1. 类型检测

      • 类型检测优先使用 typeof。对象类型检测使用 instanceofnullundefined 的检测使用 == null
      // string
      typeof variable === 'string'
      // number
      typeof variable === 'number'
      // boolean
      typeof variable === 'boolean'
      // Function
      typeof variable === 'function'
      // Object
      typeof variable === 'object'
      // RegExp
      variable instanceof RegExp
      // Array
      variable instanceof Array
      // null
      variable === null
      // null or undefined
      variable == null
      // undefined
      typeof variable === 'undefined'
      
    2. 类型转换

      • 转换成 string 时,使用 + ''
      num + '';
      
      • 转换成 number 时,通常使用 +
      +str;
      
      • string 转换成 number,要转换的字符串结尾包含非数字并期望忽略时,使用 parseInt
      var width = '200px';
      parseInt(width, 10);
      
      • 使用 parseInt 时,必须指定进制。
      parseInt(str, 10);
      
      • 转换成 boolean 时,使用 !!
      var num = 3.14;
      !!num;
      
      • number 去除小数点,使用 Math.floor / Math.round / Math.ceil,不使用 parseInt
      var num = 3.14;
      Math.ceil(num);
      
    3. 其它

      • for in 遍历对象时, 使用 hasOwnProperty 过滤掉原型中的属性。
      var newInfo = {};
      for (var key in info) {
          if (info.hasOwnProperty(key)) {
             newInfo[key] = info[key];
          }
      }
      
      • 数组排序使用 sort
      function sortNumber(a,b) {
          return a - b
      }
      // 声明数组建议 var arr = []
      // 声明指定长度数组使用下面的方式
      var arr = new Array(6)
      arr[0] = "10"
      arr[1] = "5"
      arr[2] = "40"
      arr[3] = "25"
      arr[4] = "1000"
      arr[5] = "1"
      console.log(arr);    // (6) ["10", "5", "40", "25", "1000", "1"]
      console.log(arr.sort(sortNumber)); // ["1", "5", "10", "25", "40", "1000"]
      
      • 类的继承方案,实现时需要修正 constructor
      /**
       *构建类之间的继承关系
       *@param {Function} subClass 子类函数
       *@param {Function} superClass 父类函数
       */
      var extend = function (subClass, superClass) {
          var F = function() {};
          F.prototype = superClass.prototype;
          subClass.prototype = new F();
          subClass.prototype.constructor = subClass;
          subClass.uber = C.prototype; // uber 是在模拟 class 时用来表示 super 的(因为super是关键字所以不能直接用)
      

     }
    ```

    参考链接

  • 相关阅读:
    获取Enum枚举值描述的几法方法
    c# 快速验证代理IP是否有用
    解析JSON对象与字符串之间的相互转换
    MVC4相关Razor语法以及Form表单(转载)
    MVC4数据注解和验证
    C#在Json反序列化中处理键的特殊字符
    EasyUI 兼容 IE6 方法总结
    uploadify在IE6下的问题
    Could not resolve dependencies for project, Failed to read artifact descriptor for
    shell 文本单词计数
  • 原文地址:https://www.cnblogs.com/jehorn/p/7753795.html
Copyright © 2020-2023  润新知