前端笔记
在数组原型上添加一个删除重复元素的方法
JavaScript常用操作数组方法,包含es6:https://segmentfault.com/a/1190000016503330
//第一种
<script>
var arr=[1,2,3,4,1,3];
var newArr=[];
Array.prototype.delSame=function(arr){
for(var i=0;i<arr.length;i++){
for(var j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){()
newArr.push(arr[i]);
arr.splice(i,1);
}
}
}
//删除重复之后的元素
console.log(arr);
//重复的数组元素
console.log(newArr);
}
Array.prototype.delSame(arr);
</script>
//第二种
<script>
var arr=[1,2,3,4,1,3];
Array.prototype.delSame=function(arr){
var reArr=[];
var noArr=[];
for(var i=0;i<arr.length;i++){
if(noArr.indexOf(arr[i])==-1){
noArr.push(arr[i]);
}else{
reArr.push(arr[i]);
}
}
//未重复数组
console.log(noArr);//[1, 2, 3, 4]
//重复数组
console.log(reArr);//[1, 3]
}
Array.prototype.delSame(arr);
</script>
Es6数组去重
//第一种
<script>
var arr = [1,2,3,4,1,3];
//扩展运算符
var arr2 = [... new Set(arr)];
console.log(arr2);//[1, 2, 3, 4]
</script>
//第二种
<script>
var arr = [1,2,3,4,1,3];
//类数组转数组
var arr2 = Array.from(new Set(arr));
console.log(arr2);//[1, 2, 3, 4]
</script>
计算字符串中每个字母出现次数
<script>
var str='aafeadf';
var obj={};
for(var i=0;i<str.length;i++){
var key = str[i];
if(obj[key]){
obj[key]++;
}else{
obj[key]=1;
}
}
console.log(obj);//Object {a: 3, f: 2, e: 1, d: 1}
for(var item in obj){
console.log(item +"出现了"+obj[item]+"次数");
//a出现了3次数
//f出现了2次数
//e出现了1次数
//d出现了1次数
}
</script>
每隔一秒打印输出姓名
<script>
function sayName(){
this.name='xuhao',
this.say=function(){
setInterval(function(){
console.log(this.name);
},1000);
}
//闭包
return this.say();
}
sayName();
</script>
手写冒泡排序
<script>
var arr=[1,3,2,-1,5,2,4,3];
function BubbleSort(){
for(var i=0;i<arr.length-1;i++){
for(var j=0;j<arr.length-1-i;j++){
//1与2比,2与3比...
if(arr[j]>arr[j+1]){
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
console.log(arr);
}
BubbleSort(arr);
</script>
```javascript
在这里插入代码片
jquery 使用递归实现无限级目录树
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
<style>
li{list-style:none;}
li span{display: inline-block;width:12px;height: 15px;border-radius: 50%;border: 1px solid #0000FF;vertical-align: middle;text-align: center;line-height: 15px;}
</style>
</head>
<body>
<div class="list">
</div>
<script>
var data = [{
name: "a1",
child: [{
name: "a1-1",
child: [
{ name: "a1-1-1" }, { name: "a1-1-2" }
]
}, { name: "a1-2" }, { name: "a1-3" }]
},
{ name: "a2", child: [{ name: "a2-1" }, { name: "a2-2" }] },
{ name: "a3", child: [{ name: "a3-1" }, { name: "a3-2" }] }
];
$(function() {
function create(data) {
var str = "<ul>";
for(var i = 0; i < data.length; i++) {
str += "<li><span>-</span>" + data[i].name;
if(data[i].child) {
str += create(data[i].child) + "</li>"
}
}
str += "</ul>"
return str;
}
//html嵌套
$(".list").html(create(data));
$(".list ul li").click(function(event){
//阻止事件冒泡
event.stopPropagation();
if($(this).find("ul").is(":visible")){
$(this).find("ul").hide();
$(this).find("span").text("+");
}else{
$(this).find("ul").show();
//赋值
$(this).find("span").text("-");
}
})
})
</script>
</body>
</html>
封装任意元素绑定任意事件的任意处理函数的兼容性函数
//给任意元素绑定任意事件的任意处理函数
function addEvent(elem, type, handle) {
//如果支持w3c的addEventListener
if(elem.addEventListener) {
elem.addEventListener(type, handle, false);
} else if(elem.attachEvent) {
//ie 支持attachEvent
elem.attachEvent("on" + type, function() {
//因为attachEvent的this指向window,需要借用call改变this指向
handle.call(elem);
})
} else {
elem["on" + type] = handle;
}
}
div = document.getElementsByTagName("div")[0];
function test() {
console.log("你看行不行");
}
addEvent(div,"click",test);
封装阻止事件冒泡
<script>
function stopBubble(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble=true;
}
}
div.onclick=function(e){
stopBubble(e);
}
</script>
封装阻止默认事件执行
<script>
function cancelHandle(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue=false;
}
}
//阻止默认出菜单
document.oncontextmenu=function(e){
console.log(3);
//return false;
cancelHandle(e);
}
</script>
给个数不确定的li上绑定同一事件
<script>
//事件委托利用的是事件对象和事件源对象以及冒泡的思想
//优点:不用for循环,节省性能,跟li个数无关,操作灵活
var ul = document.getElementsByTagName("ul")[0];
ul.onclick=function(event){
var e = event ||window.event;
var target = e.target||e.srcElement;
console.log(target.innerText);
}
</script>
封装获取当前计算的样式
function getStyle(ele,prop){
//不支持ie8
if(window.getComputedStyle){
return window.getComputedStyle(ele,null)[prop];
}else{
//支持ie
return ele.currentStyle[prop];
}
}
写一个计算字节长度的方法
//一个英文一个字节,一个中文2个字节
// unicode 超过255 为中文
var str = 'hello!徐';
function checkStrLen(str){
var count = str.length;
var sum =0;
for(var i=0;i<count;i++){
if(str.charCodeAt(i)<=255){
sum+=1;
}else{
sum+=2;
}
}
console.log(sum,count); //8 7
return sum;
}
checkStrLen(str);
写一个验证NaN的函数
function myIsNaN(num){
var dt = Number(num);
dt+="";
if(dt=="NaN"){
return true;
}else{
return false;
}
}
4的阶乘
var num =(function(){
if(n==1){
return 1
}
return n*arguments.callee(n-1)
}(4))
num //24
浅拷贝
var obj={name:"xj",age:16,methods:function(){
console.log("study");
},subject:['js','html']
}
var obj1={};
//空地址
function clone(orign,target){
//当用户啥也不传,默认给他一个空对象
var target=target||{};
for(var prop in orign){
target[prop]=orign[prop];
}
return target;
}
clone(obj,obj1);
深拷贝
//判断是不是原始类型
//判断是哪种引用类型
//创建对应的类型
//递归
function deepCopy(orign,target){
var arrStr='[Object Array]';
var toStr = Object.prototype.toString;
var target=target||{};
for(var prop in orign){
if(orign.hasOwnProperty(prop)){
if(orign[prop]!=="null"&&typeof(orign[prop])=="object"){
if(toStr.call(orign[prop])==arrStr){
target[prop]=[];
}else{
target[prop]={};
}
deepCopy (orign[prop],target[prop]);
}else{
target[prop]=orign[prop]
}
}
}
}
deepCopy(obj,obj2);
小方块拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div style="background: green; width: 100px;height: 100px;position: absolute;left:0;top:0;">
</div>
<script>
var div = document.getElementsByTagName("div")[0];
// div.οnmοusedοwn=function(e){
// var disX,
// disY;
// disX = e.pageX - parseInt(div.offsetLeft);
// disY = e.pageY -parseInt(div.offsetTop);
// document.οnmοusemοve=function(e){
//
// div.style.left = e.pageX-disX+"px";
// div.style.top = e.pageY-disY+"px";
// }
// document.οnmοuseup=function(){
// document.οnmοusemοve=null;
// }
// }
function stopBubble(e){
var event =e||window.event;
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble=true;
}
}
function stopDefault(e){
var event = e||window.event;
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue=false;
}
}
function addEvent(elem,type,handle){
if(elem.addEventListener){
elem.addEventListener(type,handle,false);
}else if(elem.attachEvent){
elem.attachEvent("on"+type,function(){
handle.call(elem);
});
}else{
elem["on"+type]=handle;
}
}
function removeEvent(elem,type,handle){
if(elem.removeEventListener){
elem.removeEventListener(type,handle,false);
}else if(elem.detachEvent){
elem.detachEvent("on"+type,function(){
handle.call(elem);
})
}else{
elem["on"+type]=null;
}
}
function drag(elem){
var diX,
diY;
addEvent(elem,"mousedown",function(e){
var event = e||window.event;
disX = event.clientX-parseInt(elem.style.left);
disY =event.clientY -parseInt(elem.style.top);
addEvent(document,"mousemove",mouseMove);
addEvent(document,"mouseup",mouseUp);
stopBubble(event);
stopDefault(event);
});
function mouseMove(e){
var event = e||window.event;
elem.style.left = event.pageX-disX+"px";
elem.style.top = event.pageY-disY+"px";
}
function mouseUp(e){
var event = e||window.event;
removeEvent(document,"mousemove",mouseMove);
removeEvent(document,"mouseup",mouseUp);
}
}
drag(div);
</script>
</body>
</html>
Ajax请求
$("#addP").click(function(){
$.ajax({
url:"面试题.html",
type:"get",
success:function(result){
$("#baidu").html(result);
}
});
});
//1.实例化一个ajax对象
//2.设置要传的参数,设置请求类型(判断请求类型)
//3.设置访问的url(判断有无数据)
//post设置请求头
//4发送请求
//5.获取响应的数据
var xhr = new XMLHttpRequest();
xhr.open('get','http://www.baidu.com?name'+name);
xhr.send();
xhr.onreadyStateChange=function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText)
}
}
//post
var xhr = new XMLHttpRequest();
xhr.open('post',url);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(name=xj&age=15');
xhr.onreadyStateChange=function(){
if(xhr.readyState==4&&xhr.status==200){
return xhr.responseText
}
}
function ajax_method(url,success,data,method){
var xhr = new XMLHttpRequest();
if(method=="get"){
if(data){
url+="?";
url+=data;
}else{
}
xhr.open(method,url);
xhr.send();
}else{
if(method=="get"){
xhr.open(method,url);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
if(data){
xhr.send(data);
}else{
xhr.send();
}
}
xhr.onreadyStateChange=function(){
if(xhr.readyState==4&&xhr.status==200){
success(xhr.responseText)
}
}
}