常用的js代码片段

1.单选框/手风琴

 <script>
$(document).ready(function(){
$("dd").on("click",function(){
var $this = $(this);
$("dd").removeClass("selected");
$this.addClass("selected");
})
})
</script>

2.复选框

 function checkListTwo(){    //点击变换效果
var li = document.getElementById("checkList").getElementsByTagName("li");
for(var i=0;i<li.length;i++){
li[i].onclick = function(){
if(this.className == 'selected'){
this.className = null; //单击若判断已有类,再次点击选中会清空class
}else{
this.className = 'selected';
}
}
}
}

3.多级导航菜单

 <script>
window.onload=function(){
var aLi=document.getElementsByTagName('li'); for(var i=0; i<aLi.length; i++){
aLi[i].onmouseover=function(){
//鼠标经过一级菜单,二级菜单动画下拉显示出来
var subNav=this.getElementsByTagName("ul")[0];
subNav.className='';
//alert(subNav.innerHTML);
}
//鼠标离开菜单,二级菜单动画收缩起来。
aLi[i].onmouseout=function(){
var subNav=this.getElementsByTagName("ul")[0];
subNav.className="subNav";
}
}
}
</script>

4.获取时间,把获取到的毫秒数转换成我们需要的时间格式即可

 function getFormatTime(time) {
var time = time 0; var h = parseInt(time/3600),
m = parseInt(time%3600/60),
s = parseInt(time%60);
h = h < 10 ? "0"+h : h;
m = m < 10 ? "0"+m : m;
s = s < 10 ? "0"+s : s; return h+":"+m+":"+s;
}

5.小时钟显示

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"> <title>Date</title>
</head>
<body onload="startTime()">
<script>
// var date = new Date();
// document.write(date.getFullYear()+"<br />");//年
// document.write(date.getMonth()+"<br />"); //月要加1
// document.write(date.getDate()+"<br />");//日期
// document.write(date.getDay()+"<br />"); //星期
// document.write(date.getHours()+"<br />");//时
// document.write(date.getMinutes()+"<br />");//分
// document.write(date.getSeconds()+"<br />"); //秒 function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById("timetxt").innerHTML = h+":"+m+":"+s;
t = setTimeout(function(){
startTime();
},500);
}
function checkTime(i){
if(i<10){
i = "0"+i;
}
return i;
}
</script>
<div id="timetxt"></div>
</body>
</html>

6.小写转大写

 <html>

 <head>
<script type="text/javascript">
function upperCase(x)
{
var y=document.getElementById(x).value
document.getElementById(x).value=y.toUpperCase()
}
</script>
</head> <body> Enter your name: <input type="text" id="fname" onchange="upperCase(this.id)"> </body>
</html>

7.禁止用户输入数字

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
Type some text (numbers not allowed):
<input type="text" onkeydown="return noNumbers(event)" />
</form> <script type="text/javascript">
function noNumbers(e)
{
var keynum;
var keychar;
var numcheck; if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
numcheck = /\d+/
return !numcheck.test(keychar) //把这个!去掉就是不能限制字母了
}
</script>
</body>
</html>

8.Web SQL浏览器端数据库

<html>
<head>
<meta charset="UTF-8">
<title>Web SQL</title> 
<script type="text/javascript"> var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg; db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "lucas")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.baidu.com")');
msg = '<p>数据表已创建,且插入了两条数据。</p>';
document.querySelector('#status').innerHTML = msg;
}); db.transaction(function (tx) {
tx.executeSql('DELETE FROM LOGS WHERE id=1');
msg = '<p>删除 id 为 1 的记录。</p>';
document.querySelector('#status').innerHTML += msg;
}); db.transaction(function (tx) {
tx.executeSql('UPDATE LOGS SET log=\'baidu.com\' WHERE id=2');
msg = '<p>更新 id 为 2 的记录。</p>';
document.querySelector('#status').innerHTML += msg;
}); db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>查询记录条数: " + len + "</p>";
document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
}); </script> </head> <body>
<div id="status" name="status">状态信息</div>
</body> </html>

9.一个增删demo

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一个增删demo</title>
</head>
<body>
<input type="text" id="text">
<input type="button" value="添加" id="button">
<ul>
<li>第1个<button class="btn" id="1">删除</button></li>
<li>第2个<button class="btn" id="2">删除</button></li>
<li>第3个<button class="btn" id="3">删除</button></li>
</ul>
<script>
var button = document.getElementById("button");
var text = document.getElementById("text");
var ul = document.getElementsByTagName("ul")[0];
var btnClass = document.getElementsByClassName("btn");
button.onclick = function(){
var deleteButton = document.createElement("button");
var value = text.value;
deleteButton.setAttribute("class","btn");
var deleteText = document.createTextNode("删除");
deleteButton.appendChild(deleteText);
var li = document.createElement("li");
var liText = document.createTextNode(value);
li.appendChild(liText);
li.appendChild(deleteButton);
ul.appendChild(li);
for(var i=0;i<btnClass.length;i++){
btnClass[i].onclick=function(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
}
} for(var i=0;i<btnClass.length;i++){
btnClass[i].onclick=function(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
}
</script>
</body>
</html>

10.Generator抽奖逻辑

 <script type="text/javascript">
/*generator实现抽奖逻辑*/
let draw=function(count){
console.info(`剩余${count}`);
}
let residue=function* (count){
while(count>0){
count--;
yield draw(count);
}
} let star=residue(5); //将Generator实例
star.next()
star.next()
star.next()
</script>

11.检测数据类型

//写出一个比typeof运算符更准确的类型判断函数。

var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
}; type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"
    function checkedType(target){
return Object.prototype.toString.call(target).slice(8,-1);
}
    <script>
let str=1234;
let str3=str.constructor.toString(); //返回:function Number() { [native code] }
alert(str3.slice(9,-20))
</script>

12.数组去重——Array.filter()

let arr=[2,3,4,2,3];
console.log(arr.filter(function(item,index,self){
return self.indexOf(item)==index}
)
)

注:性能差

13.数组/字符串去重——利用for循环去重

/*var arr1 ="abcdabcd";*/
var arr1=['a','b','c','a','d','b']
var arr2=[];
for(var i=0;i<arr1.length;i++){
if(arr2.indexOf(arr1[i])<0){
      arr2.push(arr1[i]);
}
}
document.write(arr2);

注:性能良好

13.1数组去重——ES6(Set)

let arr=[1,2,3,4,5,3,5,6,2];
let a=new Set(arr);
let b=[...a];
console.log(b);//[1,2,3,4,5,6]

注:性能优

13.2数组去重——创建空对象

 let arr=[1,2,3,4,5,3,5,6,2];
let b=[];
let c={};
for(let i=0;i<arr.length;i++){
if(!c[arr[i]]){
b.push(arr[i]);
c[arr[i]]='hello'; //
}
}
console.log(b);//[ 1, 2, 3, 4, 5, 6 ]
console.log(c);
/*{1: "hello", 2: "hello", 3: "hello", 4: "hello", 5: "hello", 6: "hello"}*/

注:性能最优

13.3数组去重——利用splice

function newArr(arr){
for(var i=0;i<arr.length;i++){
for(var j=i+1;j<arr.length;j++)
if(arr[i]==arr[j]){
//如果第一个等于第二个,splice方法删除第二个
arr.splice(j,1);
j--;
}
} return arr;
}
var arr = [1,1,2,5,6,3,5,5,6,8,9,8]; console.log(newArr(arr))

注:性能最差

13.4数组去重——利用filter

[1,2,3,1,'a',1,'a'].filter(function(ele,index,array){
return index===array.indexOf(ele)
})

13.4数组去重——Array.sort()

function distinct(a, b) {
let arr = a.concat(b)
arr = arr.sort()
let result = [arr[0]] for (let i=1, len=arr.length; i<len; i++) {
arr[i] !== arr[i-1] && result.push(arr[i])
}
return result;
}
console.log(distinct([4,3,2],[5,4,2])) //[2,3,4,5]

13.5字符串去重——ES6(set)

[...new Set('ababbc')].join('')
// "abc"

14.1判断数组是否存在重复值

var arr=['333','222','222','444','333'];
var s=arr.join(",")+",";
for(var i=0;i<arr.length;i++){
if(s.replace(arr[i]+",","").indexOf(arr[i]+",")>0)
alert("数组中有重复元素:" + arr[i]);
}

14.2判断数组是否存在重复值(2)

var ary = new Array("111","22","33","111");
var nary=ary.sort(); for(var i=0;i<ary.length;i++){
if (nary[i]==nary[i+1]){
alert("数组重复内容:"+nary[i]);
}
}

14.3判断数组是否存在重复值(3)

function isRepeat(arr){
var hash = [];
for(var i in arr) {
if(hash[arr[i]])
return true;
hash[arr[i]] = true;
}
return false;
} var arr=["111","22","33","111"];
alert(isRepeat(arr))

15.获取浏览URL中查询字符串的参数

 function showWindowHref(arr){
var sHref = arr;
var args = sHref.split('?');
if(args[0] == sHref){
return "";
}
var arr = args[1].split('&');
alert(arr) //staffid=12333,name=xiaoming,age=23
var obj = {};
for(var i = 0;i< arr.length;i++){
var arg = arr[i].split('=');
obj[arg[0]] = arg[1];
console.log(obj[arg[0]]) //12333,xiaomi,23
}
return obj;
}
var href = showWindowHref("https://www.runoob.com/jsref/met-win-close.html?staffid=12333&name=xiaoming&age=23"); // obj
alert(href['name']); // xiaoming

16.原生Ajax

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生的Ajax</title>
</head>
<body>
<h1></h1>
<script>
var xmlhttp;
load();
function load(){
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
}else {
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
//IE6 5
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200){
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
// 200: "OK"
// 404: 未找到页面
//responseText代表字符串形式回应 responseXML代表XML形式回应
document.getElementsByTagName('h1')[0].innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open('GET','http://www.wangwei123.cn/xx/public/admin/aside/typelist',true);//TRUE代表异步
xmlhttp.send();
}
</script>
</body>
</html>
 100——客户必须继续发出请求
101——客户要求服务器根据请求转换HTTP协议版本
200——交易成功
201——提示知道新文件的URL
202——接受和处理、但处理未完成
203——返回信息不确定或不完整
204——请求收到,但返回信息为空
205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件
206——服务器已经完成了部分用户的GET请求
300——请求的资源可在多处得到
301——删除请求数据
302——在其他地址发现了请求数据
303——建议客户访问其他URL或访问方式
304——客户端已经执行了GET,但文件未变化
305——请求的资源必须从服务器指定的地址得到
306——前一版本HTTP中使用的代码,现行版本中不再使用
307——申明请求的资源临时性删除
400——错误请求,如语法错误
401——请求授权失败
402——保留有效ChargeTo头响应
403——请求不允许
404——没有发现文件、查询或URl
405——用户在Request-Line字段定义的方法不允许
406——根据用户发送的Accept拖,请求资源不可访问
407——类似401,用户必须首先在代理服务器上得到授权
408——客户端没有在用户指定的时间内完成请求
409——对当前资源状态,请求不能完成
410——服务器上不再有此资源且无进一步的参考地址
411——服务器拒绝用户定义的Content-Length属性请求
412——一个或多个请求头字段在当前请求中错误
413——请求的资源大于服务器允许的大小
414——请求的资源URL长于服务器允许的长度
415——请求资源不支持请求项目格式
416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段
417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求
500——服务器产生内部错误
501——服务器不支持请求的函数
502——服务器暂时不可用,有时是为了防止发生系统过载
503——服务器过载或暂停维修
504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长
505——服务器不支持或拒绝支请求头中指定的HTTP版本

17.短横线转换为驼峰命名

         <script type="text/javascript">
window.onload = function() {
new Camel('border-bottom-color');
} function Camel(str) {
this.result = '';
this.arr = str.split('-');
this.result += this.arr[0].toString();
for(var i = 1; i < this.arr.length; i++) {
var str1 = this.arr[i].toString();
var str2 = str1.charAt(0).toUpperCase();
var str3 = str2 + str1.slice(1);
this.result += str3;
}
console.log(this.result); //borderBottomColor
}
</script>

18.vue实现简单购物车

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vue综合练习</title>
<style type="text/css">
td{
align-content: center;
}
</style>
</head>
<body>
<div id="app">
<h3>购物车</h3>
<h4 v-if="products.length==0">空空如也</h4>
<div v-else>
<table border="1" cellspacing="0" align="center">
<tr>
<th>编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>操作</th>
</tr>
<tr v-for="(product,index) in products">
<td>{{index+1}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td><button @click="reduce(index)">-</button>{{product.num}}<button @click="add(index)">+</button></td>
<td><button @click="del(index)">删除</button></td>
</tr
<tr>
<td colspan="5">总价:{{total}}</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="vue.js" ></script>
<script>
var app = new Vue({
el: "#app",
data: {
products:[
{id:1,name:"西瓜",price:20.00,num:4},
{id:2,name:"牛奶",price:30.00,num:2},
{id:3,name:"榴莲",price:80.00,num:1}
],
total:0
},
methods:{
//新版本写法:del(){}
//删除商品
del (index) {
this.products.splice(index,1);
this.count();
},
//减少数量
reduce (index) {
if(this.products[index].num>0){
this.products[index].num--;
this.count();
}
},
//增加商品数量
add (index){
this.products[index].num++;
this.count();
},
//计算商品总价
count () {
this.total=0;
for(var i in this.products){
this.total+=this.products[i].price*this.products[i].num;
} }
},
//最后运行
mounted(){
this.count();
}
}); </script>
</body>
</html>

18.2.vue实现简单购物车2

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:;padding:;}
.checkout-title {
position: relative;
margin-bottom: 41px;
text-align: center;
}
.checkout-title span {
position: relative;
padding: 0 1em;
background-color: #fff;
font-family: "moderat", sans-serif;
font-weight: bold;
font-size: 20px;
color: #605F5F;
z-index:;
}
.checkout-title:before{
position: absolute;
content: '';
border-bottom: 1px solid green;
width: 100%;
top:50%;
left:;
z-index:;
}
/* 居中线制作方法2
.checkout-title:before {
position: absolute; /*相对定位取决于checkout-title的position:relative
content: "";
height: 1px; //修改高度即可
width: 100%;
top: 50%;
left: 0;
background: #ccc;
z-index: 0;
}
*/
</style>
</head>
<body>
<div class="checkout-title">
<span>购物车</span>
</div>
</body>
</html>

19.vue——卡片列表循环单击选中效果

<li v-for="(item,index) in filterAddress"  v-bind:class="{'check': index == currentIndex}" @click="currentIndex=index">
/*filterAddress计算属性的方法值可以放在,充当数组*/
//@click="currentIndex=index"标明了将点击的索引值赋给currentIndex,index == currentIndex自身的索引和当前点击事件索引相同,则产生选中事件
/*当产生点击事件后,第一个currentIndex因为相等所以产生true,check类就可以渲染,v:bind和@click结合使用,会产生奇妙的状态!*/
<li v-for="(item,index) in filterAddress"  v-bind:class="{'check': index == current && current !== ' '}" @click="current=index">
/*current默认为空,然后默认不会被选中*/

注:与1的手风琴效果类似

20.深度拷贝

var deepCopy = function(obj) {
if (typeof obj !== 'object') return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
<script type="text/javascript">
/*
思考:
如何实现深度拷贝(克隆)
拷贝的数据里有对象/数组
拷贝的数据里不能有对象/数组,即使有对象/数组可以继续遍历对象、数组拿到里边每一项值,一直拿到是基本数据类型,然后再去复制,就是深度拷贝。
*/ //知识点储备
/*
如何判断数据类型:arr-Array null -Null
1.typeof返回的数据类型有:String,Number,Boolean,Undefined,Object,Function。
2.Object.prototype.toString.call(obj)。
*/ let result = 'abcd';
result = null;
result = [1,3];
console.log(Object.prototype.toString.call(result).slice(8,-1)); //[object Array],sclice截取字符串后:Array(拿到分类)。
//console.log(typeof Object.prototype.toString.call(result)); //string //for in 循环对象(属性名)、数组(下标),推荐在循环对象属性的时候,使用for...in,在遍历数组的时候的时候使用for...of。
//for in 循环遍历对象属性名
let obj = {username:'zhangsan',age:22};
for(let i in obj){
console.log(i); //username age
} //for in 循环遍历数组下标
let arr = [1,3,'abc'];
for(let i in arr){ //数组的可以用for of对应数组值
console.log(i); //0 1 2
} //定义检测数据类型的功能函数
function checkedType(target){
return Object.prototype.toString.call(target).slice(8,-1);
}
console.log(checkedType(result)); //Array //实现深度克隆--对象/数组
function clone(target){
//判断拷贝的数据类型
//初始化变量的result 成为最终克隆的数据
let result,targetType = checkedType(target);
if(targetType === 'Object'){
result = {};
}else if(targetType === 'Array'){
result = [];
}else{
return target; //如果是基本数据类型:(String, Number, boolean, Null, Undefined)就直接反回去。
} //遍历目标数据
for(let i in target){
//获取遍历数据结构的每一项值。
let value = target[i]; //i=1,i=2,i=..
//判断目标结构里的每一值是否存在对象/数组
if(checkedType(value) === 'Object' || checkedType(value) === 'Array'){ //如果对象OR数组里嵌套了对象/数组
//继续遍历获取到的value值
result[i] = clone(value); //这个只执行一次,数组里只有一个对象
}else{ //获取到的value值是基本的数据类型或者是函数。
result[i] = value; //因为arr3数组的下标0和1都是Number类型,只有下标2才是Object(转去执行1046行)
}
}
return result;
}
let arr3 = [1,2,{username:'dudu',age:32}];
let arr4 = clone(arr3); //相当于复制了一份arr3的基本数据
console.log(arr4);
arr4[2].username = 'gate';
arr4[2].age = 65;
console.log(arr3,arr4); //arr3下标2是{username:'dudu':age:32},arr4下标2是{username:gate,age:65}
</script>

21.ES6——Primise-async语法实现红绿灯

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>实现一个红绿灯</title>
<style>
#traffic-light {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid #000;
}
.traffic-box {
display: flex;
flex-direction: column;
}
.traffic {
width: 50px;
height: 50px;
margin: 5px 0;
border-radius: 50%;
border: 1px solid #000;
}
.red { background-color: red;}
.yellow { background-color: yellow;}
.green { background-color: green;}
</style>
</head>
<body>
<header>
<h1>实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色</h1>
<p>Promise、async\await 语法实现</p>
</header>
<div id="traffic-light"></div>
<hr/>
<div class="traffic-box">
<div id="traffic-red" class="traffic"></div>
<div id="traffic-yellow" class="traffic"></div>
<div id="traffic-green" class="traffic"></div>
</div>
<script>
function sleep(duration) {
return new Promise(function(reslove){
setTimeout(reslove, duration);
})
} async function changeColor(duration, color) {
document.getElementById("traffic-light").style.background = color;
await sleep(duration);
} async function main(){
while(true){
await changeColor(3000,"green");
await changeColor(1000, "yellow");
await changeColor(2000, "red");
}
}
main() //***************************************************************
var red = document.getElementById('traffic-red')
var yellow = document.getElementById('traffic-yellow')
var green = document.getElementById('traffic-green')
async function changeColor2(duration, color) {
console.log(duration, color)
if (color === 'red') {
red.classList.add('red');
yellow.classList.remove('yellow')
green.classList.remove('green')
} else if (color === 'yellow') {
yellow.classList.add('yellow');
red.classList.remove('red')
green.classList.remove('green')
} else {
green.classList.add('green');
red.classList.remove('red')
yellow.classList.remove('yellow')
}
await sleep(duration);
}
async function main2(){
while(true){
await changeColor2(3000,"green");
await changeColor2(1000, "yellow");
await changeColor2(2000, "red");
}
}
main2()
</script>
</body>
</html>

22.HTML5拖拽图片上传及本地预览

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML5拖拽上传</title>
<style>
.upload-arae {
min-width: 300px;
min-height: 150px;
border: 1px dashed #ccc;
border-radius:3px;
display: flex;
justify-content: center;
align-items: center;
color: #ccc;
margin-bottom: 10px;
}
.tip {
text-align: center;
}
.dragover {
border: 1px dashed blue;
}
.button {
color: #fff;
background-color: #20a0ff;
border-color: #20a0ff;
border-radius: 4px;
font-size: 14px;
padding: 5px 15px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>HTML5拖拽上传及本地预览</h1>
<div id="rate" class="upload-arae">
<div class="tip">
<p>将文件拖拽到此处开始上传!</p>
<label for="inputFile" class="button">选择文件</label>
<input type="file" name="file" id="inputFile" onchange="changeUpload(event)" style="display:none">
</div>
</div>
<div id="viewImg">
</div>
</body>
<script> //只能实现拖拽图片
var rate = document.getElementById('rate');
var viewImg = document.getElementById('viewImg');
document.addEventListener('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
rate.classList.add('dragover')
}, false)
document.addEventListener('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
}, false);
document.addEventListener('drop', function (e) {
e.stopPropagation();
e.preventDefault();
sendFile(e || window.event);
rate.classList.remove('dragover')
}, false);
function sendFile(e) {
var files = e.dataTransfer.files;
console.log('files', files)
if (!files || files.length < 1) {
return;
}
toViewImg(files[0])
}
function changeUpload(ev) {
let files = ev.target.files;
toViewImg(files[0])
}
function toViewImg(file) {
var reader = new FileReader();
reader.readAsDataURL(file)
reader.onload = function (e) {
viewImg.innerHTML = '上传中...'
var img = this.result
setTimeout(function(){
viewImg.innerHTML = '<img src="' + img + '" />'
}, 2000)
}
}
</script>
</html>

23.使用js实现极简Vue.js双向数据绑定功能

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>实现极简Vue.js双向数据绑定</title>
</head>
<body> <div id="app">
<input type="text" v-model="message">
{{message}}
</div> <script>
function observer(obj, vm) {
Object.keys(obj).forEach(function(key){
defineReactive(vm, key, obj[key]);
});
} function defineReactive(obj, key, val) {
var dep = new Dep();
Object.defineProperty(obj, key, {
get: function() {
console.log('Dep.target', Dep.target);
if(Dep.target) dep.addSub(Dep.target);
return val;
},
set: function(newVal) { //检测更新的时候,会自动调用并传入新值
if(newVal === val) return; //没有更新,直接返回
val = newVal;
dep.notify(); //发出通知
}
});
} function Dep() {
this.subs = [];
}
Dep.prototype = {
addSub: function(sub) {
this.subs.push(sub);
},
notify: function() {
this.subs.forEach(function(sub) {
sub.update();//更新
});
}
}; function nodeToFrangment(node, vm) { //node:ID元素
//渲染个数不确定
var flag = document.createDocumentFragment();
var child;
while(child = node.firstChild) {//逐个渲染
compile(child, vm)//解析操作
flag.append(child);
}
return flag;
} function compile(node, vm) {
var reg = /\{\{(.*)\}\}/; //正则匹配{{}}
var textType = 'input';
if(node.nodeType === 1) { //v-model
var attrs = node.attributes;
for (var i = 0; i < attrs.length; i++) {
if(attrs[i].nodeName === 'v-model') {
var name = attrs[i].nodeValue;
node.addEventListener('input', function(e){
vm[name] = e.target.value;//对数据更新,调用set方法
});
node.value = vm[name];
node.removeAttribute('v-model');
}
}
}
if(node.nodeType === 3) { //text
if(reg.test(node.nodeValue)) {
var name = RegExp.$1;
name = name.trim();
textType = 'text';
}
}
new Watcher(vm, node, name, textType);
} function Watcher(vm, node, name, nodeType) {
Dep.target = this;
this.name = name;
this.vm = vm;
this.node = node;
this.nodeType = nodeType;
this.update();
Dep.target = null;
} Watcher.prototype = {
update: function() {
this.get();
if(this.nodeType === 'text') {
this.node.nodeValue = this.value;
}
if(this.nodeType === 'input') {
this.node.value = this.value;
}
},
get: function() {//获取data中的属性值
this.value = this.vm[this.name];
}
}; function Vue(opt) { //更新数据 解析指令
this.data = opt.data;
var data = this.data;
observer(data, this); //监听数据
var id = opt.el; var dom = nodeToFrangment(document.getElementById(id), this);
document.getElementById(id).appendChild(dom);
} var v = new Vue({
el: 'app',
data: {
message: 'hello lucas'
}
});
</script>
</body>
</html>
<--! HTML代码-->
<body>
<p>
input1=><input type="text" id="input1">
</p>
<p>
input2=>
<input type="text" id="input2">
</p>
<div>
我每次比input1的值加1=>
<span id="span"></span>
</div>
</body> <--! JS代码--> var oInput1 = document.getElementById('input1');
var oInput2 = document.getElementById('input2');
var oSpan = document.getElementById('span');
var obj = {};
Object.defineProperties(obj, {
val1: {
configurable: true,
get: function() {
oInput1.value = 0;
oInput2.value = 0;
oSpan.innerHTML = 0;
return 0
},
set: function(newValue) {
oInput2.value = newValue;
oSpan.innerHTML = Number(newValue) ? Number(newValue) : 0
}
},
val2: {
configurable: true,
get: function() {
oInput1.value = 0;
oInput2.value = 0;
oSpan.innerHTML = 0;
return 0
},
set: function(newValue) {
oInput1.value = newValue;
oSpan.innerHTML = Number(newValue)+1;
}
}
})
oInput1.value = obj.val1;
oInput1.addEventListener('keyup', function() {
obj.val1 = oInput1.value;
}, false)
oInput2.addEventListener('keyup', function() {
obj.val2 = oInput2.value;
}, false)

24.左中右三栏布局,中间自适应,5种布局方法

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>左中右三栏布局,中间自适应,5种布局方法</title>
<style>
body{
margin: 0;
padding: 0;
}
/** FlexBox **/
.container{display: flex;}
.container div{min-height: 100px;}
.container .left,
.container .right{width: 300px; background-color: orange;}
.container .center{flex:1;background-color: #ccc;} /** Float **/
.container2 div{min-height: 100px;}
.container2 .left,
.container2 .right{background-color: palegreen;width: 300px;}
.container2 .center{background-color: #ccc}
.container2 .left{float: left;}
.container2 .right{float: right;} /** absolute **/
.container3{min-height: 100px;}
.container3 div{min-height: 100px;position: absolute;}
.container3 .left,
.container3 .right{background-color: palegreen;width: 300px;}
.container3 .center{background-color: #ccc;left: 300px;right: 300px;}
.container3 .left{left: 0;}
.container3 .right{right: 0;} /** table **/
.container4{width: 100%;height: 100px;display: table;}
.container4 div{display: table-cell;}
.container4 .left,
.container4 .right{background-color: palegreen;width: 300px;}
.container4 .center{background-color: #ccc;} /** CSS Grid **/
.container5{
width: 100%;
display: grid;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.container5 div{min-height: 100px;}
.container5 .left,
.container5 .right{background-color: palegreen;}
.container5 .center{background-color: #ccc;} /** 双飞翼(浮动) **/
.container6{ }
.container6 div{min-height: 100px;}
.container6 .left,
.container6 .right{background-color: palegreen;}
.container6 .center{background-color: #ccc;}
</style>
</head>
<body> <!-- 假设高度已知,左右宽度各位三百,中间自适应 -->
<h1>左中右三栏布局,中间自适应</h1>
<h2>1. FlexBox方案</h2>
<div class="container">
<div class="left"></div>
<div class="center">
左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局,
中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案
</div>
<div class="right"></div>
</div> <h2>2. Float方案</h2>
<div class="container2">
<div class="left"></div>
<div class="right"></div>
<div class="center">
左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应,
Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应
</div>
</div> <h2>3. 绝对定位方案</h2>
<div class="container3">
<div class="left"></div>
<div class="center">
左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局,
中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案
</div>
<div class="right"></div>
</div> <h2>4. 格布局方案</h2>
<div class="container4">
<div class="left"></div>
<div class="center">
左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应
左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应,
</div>
<div class="right"></div>
</div> <h2>5. 网格布局方案</h2>
<div class="container5">
<div class="left"></div>
<div class="center">
左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案
左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案
</div>
<div class="right"></div>
</div> <h2>6. 双飞翼(浮动)布局方案</h2>
<div class="container6">
<div class="main">
<div class="center">
双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案
双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案
</div>
</div>
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>

25.DIV模板引擎

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DIV模板引擎</title>
</head> <body>
<h1>DIV模板引擎</h1>
<script>
var Template = function (tempstr, data) {
var re = /<%([^%>]+)?%>/g,
cursor = 0, // 字符串的查找位置
reExp = /^\s*(for|if|else|switch|case|break|continue|{|})(.*)?/g,
code = 'var arr = [];\n';
var add = function (line, flag) { //flag --> 判断是否是JS代码
// 第一次:line ==> 我的名字是:
code += flag ? line.match(reExp) ? line : 'arr.push(' + line + ');\n'
: 'arr.push("' + line.replace(/"/, '\\"') + '");\n';
}
while (item = re.exec(tempstr)) {
add(tempstr.slice(cursor, item.index));
add(item[1], true);
cursor = item.index + item[0].length;
}
add(tempstr.substring(cursor));
code += 'return arr.join("");';
return new Function(code.replace(/[\r\n\t]/g, '')).apply(data);
} // var str = '我的名字是:<%this.name%>,年龄是:<%this.profile.age%>,Over!!!';
// var res = Template(str, {
// name: 'Dunizb',
// profile: {
// age: 22
// }
// });
// console.log(res); var str = '我的爱好:<%for(var i in this.hobby){%>'
+ '<p><%this.hobby[i]%></p>'
+ '<%}%>';
var res = Template(str, {
hobby: ['php', 'java', 'javascript', 'linux', 'python']
});
document.write(res);
</script>
</body> </html>

26.省市两级级联下拉列表

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>省市两级级联下拉列表</title>
</head>
<body>
<select id="province">
<option>==请选择省份==</option>
</select>
<select id="city">
<option>==请选择城市==</option>
</select>
</body>
<script>
// 准备数据
var data = [
{"code" : "0001", "name" : "广东省",
"cities" : [
{"code" : "00010001", "name" : "广州市"},
{"code" : "00010002", "name" : "深圳市"},
{"code" : "00010003", "name" : "东莞市"}
]
},
{"code" : "0002", "name" : "湖南省",
"cities" : [
{"code" : "00020001", "name" : "长沙市"},
{"code" : "00020002", "name" : "衡阳市"},
{"code" : "00020003", "name" : "郴州市"}
]
},
{"code" : "0003", "name" : "江西省",
"cities" : [
{"code" : "00030001", "name" : "南昌市"},
{"code" : "00030002", "name" : "赣州市"},
{"code" : "00030003", "name" : "吉安市"}
]
}
]; window.onload = function(){
// 获取省份城市select
var proSelect = document.getElementById("province");
for (var i = 0; i < data.length; i++){
var json = data[i];
var option = new Option(json.name, json.code, false, false);
proSelect.add(option);
}
// 为proSelect绑定onChange事件
proSelect.onchange = function(){
var citySelect = document.getElementById("city");
// 在下次选择省份之前先清空城市下拉列表
for (var i = citySelect.length - 1; i > 0; i--){
citySelect.remove(i);
}
for (var i = 0; i < data.length; i++){
var json = data[i];
if (json.code == this.value){
// 取城市
var cities = json.cities;
for (var j = 0; j < cities.length; j++){
// 获取其中的json
var temp = cities[j];
var option = new Option(temp.name, temp.code, false, false);
citySelect.add(option);
}
}
}
}
}
</script>
</html>

27.CSS3——打字延迟动画

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>打字动画</title>
<style>
body {background-color: #000;color:green;}
p {
width: 27em; /*这里控制打字的宽度和子长,也可以取消下面的JS注释 */
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
overflow: hidden;
white-space: nowrap;
border-right: .05em solid transparent;/*兼容处理*/
border-right: .05em solid;
animation: typing 6s steps(16),
caret 1s steps(1) infinite;
}
@keyframes typing {
from { width: 0; }
}
@keyframes caret {
50% { border-right-color: transparent; }
}
</style>
</head>
<body>
<p>Javascript是世界最好的语言,hello world,hello lucas!</p>
<script>
/*** 此段JS代码的目的是为了动态设置文字的宽度和步长 ****/ // var ps = document.getElementsByTagName("p");
// for(var i=0 ;i<ps.length; i++){
// var len = ps[i].textContent.length;
// ps[i].style.width = len + 'em';
// ps[i].style.animationTimingFunction = "steps("+len+"),steps(1)";
// }
</script>
</body>
</html>

28.CSS3——文字闪烁动画

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>文字闪烁</title>
<style>
.hightlight {
width: 500px;
margin: 100px auto;
font:700 20px/20px "Microsoft YaHei";
animation: 1s blink 3 steps(1) ;
}
@keyframes blink {
50% { color: transparent; }
}
</style>
</head>
<body>
<div class="hightlight">hello lucas</div>
</body>
</html>

29.数组与字符串对象相同的方法

concat()
indexOf()
lastIndexOf()
includes()
toString()
slice()

30.找出数组最大个数

//es5写法
function maxNumber(){
var arr = [10,29,5]
document.write(Math.max.apply(null,arr))
}
//es6拓展运算符...

Math.max(...arr)
arr.sort((num1, num2) => {
return num1 - num2 < 0
})
arr[0]
let max = arr[0];
for (let i = 0; i < arr.length - 1; i++) {
max = max < arr[i+1] ? arr[i+1] : max
}

31.JS简单数组排序

function sortNumber(a,b)
{
return a - b; //如果需要降序排序可以把a与b调换即可
} var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1" document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
    var arr = [1, 7, 10, 4, 6];
function compare(val1, val2) {
if(val1 < val2) {
return -1;
} else if(val1 > val2) {
return 1;
} else {
return 0;
}
};
arr.sort(compare);
console.log(arr);

32.对数组进行随机排序

var points = [40, 100, 1, 5, 25, 10];

function myFunction() {
return points.sort(function(a, b){return 0.5 - Math.random()}); }

33.为不具备 Iterator 接口的对象提供遍历方法

function* objectEntries(obj) {
const propKeys = Reflect.ownKeys(obj);
for (const propKey of propKeys) {
yield [propKey, obj[propKey]];
}
} const jane = { first: 'Jane', last: 'Doe' };
for (const [key,value] of objectEntries(jane)) {
console.log(`${key}: ${value}`);
}
// first: Jane
// last: Doe //Reflect.ownKeys() 返回对象所有的属性,不管属性是否可枚举,包括 Symbol。

34.嵌套数组的平铺

function* iterTree(tree) {
if (Array.isArray(tree)) {
for(let i=0; i < tree.length; i++) {
yield* iterTree(tree[i]);
}
} else {
yield tree;
}
} const tree = [ 'a', ['b', 'c'], ['d', 'e'] ]; for(let x of iterTree(tree)) {
console.log(x);
}
// a
// b
// c
// d
// e //由于扩展运算符...默认调用 Iterator 接口,所以上面这个函数也可以用于嵌套数组的平铺。 `[...iterTree(tree)] // ["a", "b", "c", "d", "e"]`

35.Markdown源码

 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>md转换为html</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>
</head> <body>
<div style="font-size: 20px;height: 30px; text-align: center;color: #009689; font-weight: bold;">Markdown转换为HTML的Demo</div>
<style>
.markdown-here-wrapper {
font-size: 16px;
line-height: 1.8em;
letter-spacing: 0.1em;
} pre,
code {
font-size: 14px;
font-family: Roboto, 'Courier New', Consolas, Inconsolata, Courier, monospace;
margin: auto 5px;
} code {
white-space: pre-wrap;
border-radius: 2px;
display: inline;
} pre {
font-size: 15px;
line-height: 1.4em;
display: block;
!important;
} pre code {
white-space: pre;
overflow: auto;
border-radius: 3px;
padding: 1px 1px;
display: block !important;
} strong,
b {
color: #BF360C;
} em,
i {
color: #009688;
} hr {
border: 1px solid #BF360C;
margin: 1.5em auto;
} p {
margin: 1.5em 5px !important;
} table,
pre,
dl,
blockquote,
q,
ul,
ol {
margin: 10px 5px;
} ul,
ol {
padding-left: 15px;
} li {
margin: 10px;
} li p {
margin: 10px 0 !important;
} ul ul,
ul ol,
ol ul,
ol ol {
margin: 0;
padding-left: 10px;
} ul {
list-style-type: circle;
} dl {
padding: 0;
} dl dt {
font-size: 1em;
font-weight: bold;
font-style: italic;
} dl dd {
margin: 0 0 10px;
padding: 0 10px;
} blockquote,
q {
border-left: 2px solid #009688;
padding: 0 10px;
color: #777;
quotes: none;
margin-left: 1em;
} blockquote::before,
blockquote::after,
q::before,
q::after {
content: none;
} h1,
h2,
h3,
h4,
h5,
h6 {
margin: 20px 0 10px;
padding: 0;
font-style: bold !important;
color: #009688 !important;
text-align: center !important;
margin: 1.5em 5px !important;
padding: 0.5em 1em !important;
} h1 {
font-size: 24px !important;
border-bottom: 1px solid #ddd !important;
} h2 {
font-size: 20px !important;
border-bottom: 1px solid #eee !important;
} h3 {
font-size: 18px;
} h4 {
font-size: 16px;
} table {
padding: 0;
border-collapse: collapse;
border-spacing: 0;
font-size: 1em;
font: inherit;
border: 0;
margin: 0 auto;
} tbody {
margin: 0;
padding: 0;
border: 0;
} table tr {
border: 0;
border-top: 1px solid #CCC;
background-color: white;
margin: 0;
padding: 0;
} table tr:nth-child(2n) {
background-color: #F8F8F8;
} table tr th,
table tr td {
font-size: 16px;
border: 1px solid #CCC;
margin: 0;
padding: 5px 10px;
} table tr th {
font-weight: bold;
color: #eee;
border: 1px solid #009688;
background-color: #009688;
}
</style>
<style>
#area>table {
width: 100%;
table-layout: fixed;
} #area table tr td {
margin: 0;
padding: 6px;
border: 0; } #md-area { width: 100%;
height: 600px;
font-size: 18px;
overflow: hidden;
font-weight: bold;
outline: none;
} #show-area {
height: 600px;
background-color: #FCF6E5;
} .clearfix:before {
content: "";
display: table;
}
</style>
<script>
function mdSwitch() {
var mdValue = document.getElementById("md-area").value;
var converter = new showdown.Converter();
var html = converter.makeHtml(mdValue);
document.getElementById("show-area").innerHTML = html;
}
</script>
<div id="area">
<table>
<tr>
<td><textarea name="" id="md-area" onkeyup=mdSwitch()></textarea></td>
<td>
<div id="show-area" class="clearfix"></div>
</td>
</tr>
</table>
</div>
</body> </html>

36.筛选数组数据

<script type="text/javascript">
//创建数组
var arr = ['*','##',"***","&&","****","##*"];
arr[7] = "**";
//数组长度
var l = arr.length; //删除数组中非*的项 for(var i = 0; i < l; i++){
var val = arr[i]; if(val != undefined) {
var newarr = val.split('');
var newl = newarr.length;
for(var j = 0; j < newl; j++){
if(newarr[j] != '*'){
arr.splice(i, 1);
break;
}
}
}
} //按照字符数排序
arr.sort(function(a, b){
if(a.length > b.length){
return 1
}else if(a.length < b.length){
return -1
}else{
return 0
}
}) //将数组内容输出,完成达到的效果。
for(var i = 0; i < l; i++){
if(arr[i] != undefined){
document.write(arr[i] + '<br />')
}
}
</script>
<script type="text/javascript">

 //第一步把之前的数据写成一个数组的形式,定义变量为 infos
var infos=[
['小A','女',21,'大一'],
['小B','男',23,'大三'],
['小C','男',24,'大四'],
['小C','男',24,'大四'],
['小D','女',21,'大一'],
['小E','女',22,'大四'],
['小F','男',21,'大一'],
['小G','女',22,'大二'],
['小H','女',20,'大三'],
['小I','女',20,'大一'],
['小J','男',20,'大三']
]; //第一次筛选,找出都是大一的信息
var i=0;
var length=infos.length;
for(i=0;i<length;i++){
if(infos[i][3]=='大一'&&infos[i][1]=='女'){
document.write(infos[i][0] + "&nbsp&nbsp"+ infos[i][3]+"</br>");
} } //第二次筛选,找出都是女生的信息 </script>

37.简单加减乘除计算器

 <!DOCTYPE html>
<html>
<head>
<title>加减乘除计算器</title>
<script type="text/javascript">
function count(){ //获取第一个输入框的值
var a=document.getElementById("txt1").value;
//获取第二个输入框的值
var b=document.getElementById("txt2").value;
//获取选择框的值
var c=document.getElementById("select").value;
var sum="";
switch(c)
{
case '+':
sum=parseFloat(a) + parseFloat(b);
break;
case '-':
sum=parseFloat(a) - parseFloat(b);
break;
case '*':
sum=parseFloat(a) * parseFloat(b);
break;
default:
sum=parseFloat(a) / parseFloat(b);
break; }
document.getElementById("fruit").value=sum;
}
</script>
</head>
<body>
<input type='text' id='txt1' />
<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='text' id='txt2' />
<input type='button' value=' = ' onclick="count()" /> <!--通过 = 按钮来调用创建的函数,得到结果-->
<input type='text' id='fruit' />
</body>
</html>

38.js实现随机选取10——100之间的10个数字

var iArray=[];

function getRandom(istart,iend){
        var iChoice=istart-iend+1;         return Math.floor(Math.random()*iChoice+istart);
} for(var i=0;i<10;i++){         iArray.push(getRandom(10,100)); } iArray.sort()

39.删除数组中的null、undefined以及empty值

var a=[123, undefined, undefined, undefined, 8567, 213];
var b = [];//去除undefined后的结果 for(var i=0;i<a.length;i++){
if(typeof(a[i])!='undefined'){ //或者a[i]!='undefined'
b.push(a[i]);
}
}
/*1只删除存在undefined和empty(空数组)的数组*/
let arr1 = [123, undefined, undefined, undefined, 8567, empty, 213];
//empty不能直接设置,是通过delete arr1[5]来产生的 arr2 = arr1.filter(function(item,index,arr){
return typeof arr[index] != 'undefined'
})
//[123, 8567, 213] /*2.只删除存在有null的数组*/
let arr1 = [533, 213, null, 237, empty, 789]; arr2 = arr1.filter(function(item,index,arr){
return arr[index] != null
})
// [533, 213, 237, 789] /*3.同时删除存在undefined、empty以及null的数组*/ let arr1 = [123, undefined, empty, 8567, null, null, 213];
let arr2 = []; for(let i =0;i<arr1.length;i++){
if(arr1[i]!=undefined || arr1[i]!=null) //注意undefined不能加引号
arr2.push(arr1[i])
}
//[123, 8567, 213]

40.计算各个字符串出现的次数

 //1.计算成数组
function strNubAry(str){
var ary = [];
fnFas(str); function fnFas(str){
var s1 = str.charAt(0); //首次得到数字2,第二次递归得到数字3
var _str = '';
var n = 0; //存放每个字符被计算出现的数量 //每for循环结束都只获得一个数组元素(被计算字符=次数)
for (var i = 0; i < str.length; i++) {
if(str.charAt(i) == s1){
n++;
}else{
_str += str.charAt(i); //语句首次被执行获得字符是3
// console.log("i="+i+" s1=="+s1+" _str="+_str); //试数
}
} ary.push(s1+'='+n) //首次执行到此处_str.length长度等于28(_str值除了数字2以外)
if(_str.length > 0){
fnFas(_str); //递归
}
} return ary;
} var str = '2231452erfsdg35@#¥%63erefds我是大神'; console.log(strNubAry(str)); /* 输出结果各个字符出现的次数:
[
"2=3", "3=3", "1=1", "4=1", "5=2", "e=3", "r=2", "f=2", "s=2", "d=2", "g=1",
"@=1", "#=1", "¥=1", "%=1", "6=1", "我=1", "是=1", "大=1", "神=1"
]
*/ //2.计算成对象
function strNubObj(str){
var obj = {};
var ary = [];
fnFas(str);
function fnFas(str){
var s1 = str.charAt(0);
var _str = '';
var n = 0; for (var i = 0; i < str.length; i++) {
if(str.charAt(i) == s1){
n++;
}else{
_str += str.charAt(i);
}
}
try{
eval('obj.'+s1+'='+n)
}catch(err){
ary.push(s1+'='+n)
} if(_str.length > 0){
fnFas(_str);
}
} if(ary.length > 0){
obj.aNumber = ary;
}
return obj;
}
 var arr = "1111245742157";
var count = 0;
var czarr = "";
for (var i = 0; i < arr.length; i++) {
for (var o = 0; o < arr.length; o++) {
if (parseInt(arr.charAt(i)) == parseInt(arr[o])) {
count++;
}
}
console.log(+arr.charAt(i)+"==="+count) if (count > 1) {
czarr += arr.charAt(i);
}
count = 0;
}

41. Vue根据文件名引入组件

// 1.场景:如页面需要导入多个组件,原始写法:

import titleCom from '@/components/home/titleCom'
import bannerCom from '@/components/home/bannerCom'
import cellCom from '@/components/home/cellCom'
components:{titleCom,bannerCom,cellCom} // 2.这样就写了大量重复的代码,利用 require.context 可以写成:
const path = require('path')
const files = require.context('@/components/home', false, /\.vue$/)
const modules = {}
files.keys().forEach(key => {
const name = path.basename(key, '.vue')
modules[name] = files(key).default || files(key)
})
components:modules // 这样不管页面引入多少组件,都可以使用这个方法

待续......

上一篇:Linux转发性能评估与优化-转发瓶颈分析与解决方式(补遗)


下一篇:C++并发编程 等待与唤醒