freecodecamp第4章学习记录和js类型判断总结

jQuery代码释义

  • $(document).ready(function(){}) //等价于window.onload
  • $(‘element’).addClass(‘class1 class2’) //选择元素,添加class

    • 选择元素$(”h1”)
    • 选择class$(“.class”)
    • 选择id$(“#id”)
  • 删除class removeClass()

    • $(“#id”).removeClass(“class1”)
  • 替换css样式 .css()
    • $(“#id”).css(“color”, “red”)
  • 使元素失效.prop(“disabled”, true)

    • $(“#id”).prop(“disabled”, true)
  • .html()可以改变标签和标签内的内容

    • $(”h3”).html(“<h1>123</h1> “) //把h3标签以及标签内的内容全部替换为好h1和123
  • .text()只改变标签里的内容,无法改变原标签
  • .remove() 与removeClass()相似,只不过这次移除的是html上的元素,不需要传参数
    • $(#id1).remove() //把id1这个元素从html的dom里移除了
  • .appendTo() 把一个元素添加到另一个元素内部的最后一位
    • $(“#id1”).appendTo(“#id2”) 把id1这个元素移到id2这个元素的内部
  • .clone() 克隆一个元素,一般与.appendTo()一起使用
    • $(“#id1”).clone().appendTo(“#id2”) 把id1元素克隆一份添加到id2的最末尾
  • .parent() 返回选取元素的父元素
    • $(“#id1”).parent() 返回id1元素的父元素
  • .children() 和parent()相似,但是可以接受一个参数
    • $(“#id1”).children(“div#id2”) 选取id1元素下的id为id2的div,()内可以指定标签+id或者class精确定位
  • 用css的nth-child(n)来选择元素
    • $(“.class1:nth-child(2)”) 选中有类class1的元素中的第二个元素
    • $(“.class1:odd”)选择奇数,(从0开始)偶数用even

typeof

  • 可以识别标准类型(Null由于历史原因显示object)
  • 不能识别具体的对象类型(function除外)
类型 实例 typeof
Undefined undefined “undefined”
Null null “object”
Boolean true “boolean”
String “hello” “string”
Number 123 “number”
Function Math.sin “function”
Symbol Symbol() “symbol”
Array [1, 2, 3] “object”
Object any other object “object”

Object.prototype.toString

  • 可以识别标准类型和内置对象类型
  • 不可识别自定义类型
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var toString = Object.prototype.toString;
    toString.call(new Date); // "[object Date]"
    toString.call(new String); // "[object String]"
    toString.call(new Number); // "[object Number]"
    toString.call(new Array); // "[object Array]"
    toString.call(new Object); // "[object Object]"
    toString.call(new Boolean); // "[object Boolean]"
    toString.call(new Function); // "[object Function]"
    toString.call(Symbol()); // "[object Symbol]"
    toString.call(undefined); // "[object Undefined]"
    toString.call(null); // "[object Null]"

constructor

  • 可以识别标准类型(Undefined/Null除外)
  • 可以识别内置对象类型
  • 可以识别自定义对象类型
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var Person = {};
    var arr = [];
    function getConstructorName(obj) {
    return obj && obj.constructor && obj.constructor.toString().match(/function\s*([^(]*)/)[1];
    }
    getConstructorName(Person) // "Object" 自定义对象
    getConstructorName(arr) // "Array" 自定义数组
    getConstructorName(new Date) // "Date" 内置对象
    getConstructorName(123) // "Number" 标准类型

instanceof

  • 不可判断原始类型
  • 可以判断内置对象类型
  • 可以判断自定义对象类型
    ```js
    var Person = {};
    var myDate = new Date();

Person instanceof Object // true 自定义对象
123 instanceof Number // false 原始类型
myDate instanceof Date // true 内置对象类型
```
汇总如下(图片来自前端开发笔记本