数组 Array
javascript中的Array并不是在内存中连续存储的,它的数组是哈希映射,可以存放不同类型元素、数组长度可变。这些特性与一般的数组完全不一样。
let a1 = []undefinedlet a2 = new Array(2)undefineda1[0] = 1212a1[1] = '33''33'a1(2) [12, '33']a2[0] = 1212a2[1] = '33''33'a2(2) [12, '33']a1 == a2falsetypeof(a1)'object'typeof(a2)'object'
这个数组其实是一种特殊的对象,内部也是key-value的存储形式
数组的常用方法
对象 Object
对象的拷贝
对象是引用类型,通过赋值,只能拷贝对象在内存中的位置指针,这样的话,修改了拷贝对象,就等于修改了源对象。
var obj = {x : 0};obj.x = 100;var o = obj; //实际拷贝的是obj的内存地址o.x = 1;console.log(obj.x) // 1, obj被修改
若想拷贝得到一个新的对象,则要用其他方法。
- 浅拷贝,遍历对象,进行复制子元素
- 深拷贝,由于子元素中也可能含有对象。。。
- 用
JSON.parse(JSON.stringify(originOBJ))将对象转为JSON,再转为对象来实现拷贝。有两个缺点:一是不支持Function、Date等数据类型;二是不支持循环引用。(循环引用是啥?) - 递归遍历
function deepCopy(origin, target) {target = target || {};for (let i in origin) {if (origin.hasOwnProperty(i)) {if (typeof origin[i] === 'object') {target[i] = Array.isArray(origin[i]) ? [] : {};deepCopy(origin(i), target(i));} else {target(i) = origin(i);}}}return target;}
- 用
简单操作
- 获取页面节点:
document.getElementById('id'); // 无#document.getElementsByClassName("class"); // 无. 返回的是数组document.getElementsByTagName("tagname"); // 获取的似乎不是数组
- 数组操作:
array.push(值); // 向数组里面插入值array.join('&'); // 把数组用特定字符连接,变成一个字符串
- 添加子节点、移除子节点:
父节点.appendChild(子节点); 父节点.removeChild(子节点); - 创建新节点, 之后设置它的一些属性:
var newNode = document.createElement('div');// 是一对标签内含的文字,比如 <a href = "#">innerText</a>newNode.innerText = 'abc';newNode.class = 'abc';newNode.style.curcor = 'pointer';newNode.style.margine = '5px';newNode.style.display = 'none';newNode.style.textIntent = '2em'; // 段的开头空两格
鼠标移入、鼠标移出、鼠标点击事件
Obj.onmouseover = function () {this.style.backgroundColor = '#c1f9e5';};Obj.onmouseout = function () {this.style.backgroundColor = '';};Obj.onclick = function () {txt.value = this.innerText;dvObj.display = 'none';};
添加监听事件:
txt.addEventListener("input",handle,false);
handle是一个函数,input是事件类型。
- 当某个结点加载时(一般是body),调用某函数
onload="threeStart();"
jQuery
- 点击事件:
$('.class').on('click', function () { }$("#btn1").click(function(){ }
- 判断是否有这个类:
$("body").hasClass("cls") == true;
- 移除、添加这个类;切换类
$("body").removeClass("cls");$("body").addClass("cls");$("body").toggleClass("cls"); // -如果已有则删除,没有则添加
- 设置或获取标签的内夹文字,需要这个标签有
value这个属性
// 比如,<input type="button" id='btn' value='按钮' >$(selector).val()=="文字"; // 获取$(selector).val("文字"); // 写入
- 添加样式
$("selector").css("样式名字", "值");$("body").css("backgroundColor","#555");$(".cre div").css("border","1px solid #ccc");$(".cre div").css("width","200px");$(".cre div").css("height","200px");// 链式编程$('selector').css(,).css(,)...;$(".cre div").css("backgroundColor","GreenYellow").css("border","1px solid #ccc").css("width","200px").css("height","200px");// json形式,一起写var ojson = {"backgroundColor":"GreenYellow","border":"2px solid #eee","width":"250px","height":"250px"};$(".cre div").css(ojson);
- 鼠标移入事件
$("#id").mouseenter(function(){ }
- 显示、隐藏
$("selector").hide();$("selector").show();
- 添加新节点
// 子结点 添加进 父节点$("子selector").appendTo($("父selector"));// 父节点 添加 子节点$('父selector').append($("子selector"));
- 链式编程设置方法, 对象.方法().方法().方法();
// 对象调用方法,如果返回值还是当前这个对象那么久可以继续调用方法// 一般,可链式调用的方法是设置某属性/* for example */$("#rightdiv>ul>li").mouseenter(function(){ //鼠标进入事件$(this).css("backgroundColor","#aeaeae").siblings("li").css("backgroundColor","");}).mouseleave(function(){ //鼠标离开事件$(this).css("backgroundColor","").siblings("li").css("backgroundColor","");}).click(function(){ //点击事件//注意下面两句不能写成链式$(this).prevAll("li").css("backgroundColor","aqua");$(this).nextAll("li").css("backgroundColor","pink");});
- 获取兄弟元素
//下一个$(this).next("li").css("backgroundColor","aqua");//前一个$(this).prev("li").css("backgroundColor","#123");//后面所以$(this).nextAll("li").css("backgroundColor","pink");//前面所有$(this).prevAll("li").css("backgroundColor","GreenYellow");//所有兄弟元素 不包括自己$(this).siblings("li").css("backgroundColor","gray");
- 获取其他的一些元素
//某元素.perant()---->父级元素//某元素.children()---->直接子元素//某元素.find("选择器")----->从当前元素中找某些元素
- 简单动画, 可传时间参数(ms)和回调函数
//.show()----.hide()//.slideUp()----.slideDown()//.slideToggle()切换划入和划出//.fadeIn()----.fadeOut()淡入 淡出//.fadeToggle() 切换//.fadeTo()--参数为(时间,透明度)//.animation() 参数1:键值对;参数2:时间;参数3:回调函数。
原生js与jquery相同功能的比较
- 获取结点:
/* ys */document.getElementById("直接写id名字");/* jq */$("#id 或者 .class 或者 标签名");$(this);
- 获取一对结点里面的内容
/* ys */document.getElementById("直接写id名字").value;用原生方式获取的节点.value;/* jq */$("selector").val();
ajax
原生js的ajax
// 1.创建一个异步对象var xhr;//解决ie兼容性if(window.XMLHttpRequest){xhr = new XMLHttpRequest();}else{xhr = new ActiveXObject('Microsoft.XMLHTTP');}// GET/POST 获取方式; 文件; 是否xxxhr.open('GET','11.php',true);// 发送请求xhr.send();// 当状态改变时xhr.onreadystatechange = function(){if (this.readyState !== 4) return;console.log(this.responseText);}// 给xhr对象设置监听事件,监测readyState改变的各个数值xhr.addEventListener('readystatechange', function () {switch (this.readyState) {case 2:// => 2// 已经接受到了响应报文的响应头// 但是还没有拿到体console.log(this.responseText);break;case 3:// => 3// 正在下载响应报文的响应体,有可能响应体为空,也有可能不完整// 在这里处理响应体不保险(不可靠)console.log(this.responseText);break;case 4:// => 4// 一切 OK (整个响应报文已经完整下载下来了)console.log(this.responseText);// this.responseText 就是获取到的数据break;}})
jQuery封装ajax
$.ajax({// 文件路径url: '05-time.php',// 请求方式type: 'get',// 数据类型dataType: 'json',//用于提交到服务端的参数//如果是 GET请求 则通过url传递//如果是 POST请求 则通过请求体传递data: { id : 1, name : 'zs'},beforeSend: function (xhr) {// 请求发送之前执行console.log('beforeSend');},// 请求成功,data就是获得的数据success: function (data) {console.log(data);},error: function (err) {console.log(err);},complete: function (xhr) {// 不管请求成功或者是失败,都执行console.log(xhr);}})
// 1. get方式请求// 语法: $.get(URL,data,function(data,status,xhr),dataType);/** URL-必选,请求的url* data-可选,连同请求发送到服务器的数据* function-可选,data - 包含来自请求的结果数据status - 包含请求的状态("success"、"notmodified"、"error"、"timeout"、"parsererror")xhr - 包含 XMLHttpRequest 对象* dataType-可选,规定预期的服务器响应的数据类型,xml,html,text,script,json;*/// '{ id: 1}' 发送请求数据,function是回掉函数$.get('time.php',{ id: 1}, function (res) {console.log(res);});//2. post方式请求// 语法:$.post(URL,data,function(data,status,xhr),dataType)// 参数同上$.post('time.php', { id: 1}, function (res) {console.log(res);});
