数组 Array

javascript中的Array并不是在内存中连续存储的,它的数组是哈希映射,可以存放不同类型元素、数组长度可变。这些特性与一般的数组完全不一样。

  1. let a1 = []
  2. undefined
  3. let a2 = new Array(2)
  4. undefined
  5. a1[0] = 12
  6. 12
  7. a1[1] = '33'
  8. '33'
  9. a1
  10. (2) [12, '33']
  11. a2[0] = 12
  12. 12
  13. a2[1] = '33'
  14. '33'
  15. a2
  16. (2) [12, '33']
  17. a1 == a2
  18. false
  19. typeof(a1)
  20. 'object'
  21. typeof(a2)
  22. 'object'

这个数组其实是一种特殊的对象,内部也是key-value的存储形式

数组的常用方法

对象 Object

对象的拷贝

对象是引用类型,通过赋值,只能拷贝对象在内存中的位置指针,这样的话,修改了拷贝对象,就等于修改了源对象。

  1. var obj = {x : 0};
  2. obj.x = 100;
  3. var o = obj; //实际拷贝的是obj的内存地址
  4. o.x = 1;
  5. console.log(obj.x) // 1, obj被修改

若想拷贝得到一个新的对象,则要用其他方法。

  1. 浅拷贝,遍历对象,进行复制子元素
  2. 深拷贝,由于子元素中也可能含有对象。。。
    1. JSON.parse(JSON.stringify(originOBJ))将对象转为JSON,再转为对象来实现拷贝。有两个缺点:一是不支持Function、Date等数据类型;二是不支持循环引用。(循环引用是啥?)
    2. 递归遍历
      1. function deepCopy(origin, target) {
      2. target = target || {};
      3. for (let i in origin) {
      4. if (origin.hasOwnProperty(i)) {
      5. if (typeof origin[i] === 'object') {
      6. target[i] = Array.isArray(origin[i]) ? [] : {};
      7. deepCopy(origin(i), target(i));
      8. } else {
      9. target(i) = origin(i);
      10. }
      11. }
      12. }
      13. return target;
      14. }

简单操作

  • 获取页面节点:
  1. document.getElementById('id'); // 无#
  2. document.getElementsByClassName("class"); // 无. 返回的是数组
  3. document.getElementsByTagName("tagname"); // 获取的似乎不是数组
  • 数组操作:
  1. array.push(值); // 向数组里面插入值
  2. array.join('&'); // 把数组用特定字符连接,变成一个字符串
  • 添加子节点、移除子节点: 父节点.appendChild(子节点); 父节点.removeChild(子节点);
  • 创建新节点, 之后设置它的一些属性:
  1. var newNode = document.createElement('div');
  2. // 是一对标签内含的文字,比如 <a href = "#">innerText</a>
  3. newNode.innerText = 'abc';
  4. newNode.class = 'abc';
  5. newNode.style.curcor = 'pointer';
  6. newNode.style.margine = '5px';
  7. newNode.style.display = 'none';
  8. newNode.style.textIntent = '2em'; // 段的开头空两格
  • 鼠标移入、鼠标移出、鼠标点击事件

    1. Obj.onmouseover = function () {
    2. this.style.backgroundColor = '#c1f9e5';
    3. };
    4. Obj.onmouseout = function () {
    5. this.style.backgroundColor = '';
    6. };
    7. Obj.onclick = function () {
    8. txt.value = this.innerText;
    9. dvObj.display = 'none';
    10. };
  • 添加监听事件:

  1. txt.addEventListener("input",handle,false);

handle是一个函数,input是事件类型。

  • 当某个结点加载时(一般是body),调用某函数
  1. onload="threeStart();"

jQuery

  • 点击事件:
  1. $('.class').on('click', function () { }
  2. $("#btn1").click(function(){ }
  • 判断是否有这个类:
  1. $("body").hasClass("cls") == true;
  • 移除、添加这个类;切换类
  1. $("body").removeClass("cls");
  2. $("body").addClass("cls");
  3. $("body").toggleClass("cls"); // -如果已有则删除,没有则添加
  • 设置或获取标签的内夹文字,需要这个标签有value这个属性
  1. // 比如,<input type="button" id='btn' value='按钮' >
  2. $(selector).val()=="文字"; // 获取
  3. $(selector).val("文字"); // 写入
  • 添加样式
  1. $("selector").css("样式名字", "值");
  2. $("body").css("backgroundColor","#555");
  3. $(".cre div").css("border","1px solid #ccc");
  4. $(".cre div").css("width","200px");
  5. $(".cre div").css("height","200px");
  6. // 链式编程
  7. $('selector').css(,).css(,)...;
  8. $(".cre div").css("backgroundColor","GreenYellow").css("border","1px solid #ccc").css("width","200px").css("height","200px");
  9. // json形式,一起写
  10. var ojson = {"backgroundColor":"GreenYellow","border":"2px solid #eee","width":"250px","height":"250px"};
  11. $(".cre div").css(ojson);
  • 鼠标移入事件
  1. $("#id").mouseenter(function(){ }
  • 显示、隐藏
  1. $("selector").hide();
  2. $("selector").show();
  • 添加新节点
  1. // 子结点 添加进 父节点
  2. $("子selector").appendTo($("父selector"));
  3. // 父节点 添加 子节点
  4. $('父selector').append($("子selector"));
  • 链式编程设置方法, 对象.方法().方法().方法();
  1. // 对象调用方法,如果返回值还是当前这个对象那么久可以继续调用方法
  2. // 一般,可链式调用的方法是设置某属性
  3. /* for example */
  4. $("#rightdiv>ul>li").mouseenter(function(){ //鼠标进入事件
  5. $(this).css("backgroundColor","#aeaeae").siblings("li").css("backgroundColor","");
  6. }).mouseleave(function(){ //鼠标离开事件
  7. $(this).css("backgroundColor","").siblings("li").css("backgroundColor","");
  8. }).click(function(){ //点击事件
  9. //注意下面两句不能写成链式
  10. $(this).prevAll("li").css("backgroundColor","aqua");
  11. $(this).nextAll("li").css("backgroundColor","pink");
  12. });
  • 获取兄弟元素
  1. //下一个
  2. $(this).next("li").css("backgroundColor","aqua");
  3. //前一个
  4. $(this).prev("li").css("backgroundColor","#123");
  5. //后面所以
  6. $(this).nextAll("li").css("backgroundColor","pink");
  7. //前面所有
  8. $(this).prevAll("li").css("backgroundColor","GreenYellow");
  9. //所有兄弟元素 不包括自己
  10. $(this).siblings("li").css("backgroundColor","gray");
  • 获取其他的一些元素
  1. //某元素.perant()---->父级元素
  2. //某元素.children()---->直接子元素
  3. //某元素.find("选择器")----->从当前元素中找某些元素
  • 简单动画, 可传时间参数(ms)和回调函数
  1. //.show()----.hide()
  2. //.slideUp()----.slideDown()
  3. //.slideToggle()切换划入和划出
  4. //.fadeIn()----.fadeOut()淡入 淡出
  5. //.fadeToggle() 切换
  6. //.fadeTo()--参数为(时间,透明度)
  7. //.animation() 参数1:键值对;参数2:时间;参数3:回调函数。

原生js与jquery相同功能的比较

  • 获取结点:
  1. /* ys */
  2. document.getElementById("直接写id名字");
  3. /* jq */
  4. $("#id 或者 .class 或者 标签名");
  5. $(this);
  • 获取一对结点里面的内容
  1. /* ys */
  2. document.getElementById("直接写id名字").value;
  3. 用原生方式获取的节点.value;
  4. /* jq */
  5. $("selector").val();

ajax

原生js的ajax

  1. // 1.创建一个异步对象
  2. var xhr;
  3. //解决ie兼容性
  4. if(window.XMLHttpRequest){
  5. xhr = new XMLHttpRequest();
  6. }else{
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  8. }
  9. // GET/POST 获取方式; 文件; 是否xx
  10. xhr.open('GET','11.php',true);
  11. // 发送请求
  12. xhr.send();
  13. // 当状态改变时
  14. xhr.onreadystatechange = function(){
  15. if (this.readyState !== 4) return;
  16. console.log(this.responseText);
  17. }
  18. // 给xhr对象设置监听事件,监测readyState改变的各个数值
  19. xhr.addEventListener('readystatechange', function () {
  20. switch (this.readyState) {
  21. case 2:
  22. // => 2
  23. // 已经接受到了响应报文的响应头
  24. // 但是还没有拿到体
  25. console.log(this.responseText);
  26. break;
  27. case 3:
  28. // => 3
  29. // 正在下载响应报文的响应体,有可能响应体为空,也有可能不完整
  30. // 在这里处理响应体不保险(不可靠)
  31. console.log(this.responseText);
  32. break;
  33. case 4:
  34. // => 4
  35. // 一切 OK (整个响应报文已经完整下载下来了)
  36. console.log(this.responseText);
  37. // this.responseText 就是获取到的数据
  38. break;
  39. }
  40. })

jQuery封装ajax

  1. $.ajax({
  2. // 文件路径
  3. url: '05-time.php',
  4. // 请求方式
  5. type: 'get',
  6. // 数据类型
  7. dataType: 'json',
  8. //用于提交到服务端的参数
  9. //如果是 GET请求 则通过url传递
  10. //如果是 POST请求 则通过请求体传递
  11. data: { id : 1, name : 'zs'},
  12. beforeSend: function (xhr) {
  13. // 请求发送之前执行
  14. console.log('beforeSend');
  15. },
  16. // 请求成功,data就是获得的数据
  17. success: function (data) {
  18. console.log(data);
  19. },
  20. error: function (err) {
  21. console.log(err);
  22. },
  23. complete: function (xhr) {
  24. // 不管请求成功或者是失败,都执行
  25. console.log(xhr);
  26. }
  27. })
  1. // 1. get方式请求
  2. // 语法: $.get(URL,data,function(data,status,xhr),dataType);
  3. /*
  4. * URL-必选,请求的url
  5. * data-可选,连同请求发送到服务器的数据
  6. * function-可选,
  7. data - 包含来自请求的结果数据
  8. status - 包含请求的状态("success"、"notmodified"、"error"、"timeout"、"parsererror")
  9. xhr - 包含 XMLHttpRequest 对象
  10. * dataType-可选,规定预期的服务器响应的数据类型,xml,html,text,script,json;
  11. */
  12. // '{ id: 1}' 发送请求数据,function是回掉函数
  13. $.get('time.php',{ id: 1}, function (res) {
  14. console.log(res);
  15. });
  16. //2. post方式请求
  17. // 语法:$.post(URL,data,function(data,status,xhr),dataType)
  18. // 参数同上
  19. $.post('time.php', { id: 1}, function (res) {
  20. console.log(res);
  21. });