1 <script> 2 $(document).ready(function(){ 3 $("dd").on("click",function(){ 4 var $this = $(this); 5 $("dd").removeClass("selected"); 6 $this.addClass("selected"); 7 }) 8 }) 9 </script>
1 function checkListTwo(){ //點擊變換效果 2 var li = document.getElementById("checkList").getElementsByTagName("li"); 3 for(var i=0;i<li.length;i++){ 4 li[i].onclick = function(){ 5 if(this.className == 'selected'){ 6 this.className = null; //單擊若判斷已有類,再次點擊選中會清空class 7 }else{ 8 this.className = 'selected'; 9 } 10 } 11 } 12 }
1 <script> 2 window.onload=function(){ 3 var aLi=document.getElementsByTagName('li'); 4 5 for(var i=0; i<aLi.length; i++){ 6 aLi[i].onmouseover=function(){ 7 //鼠標通過一級菜單,二級菜單動畫下拉顯示出來 8 var subNav=this.getElementsByTagName("ul")[0]; 9 subNav.className=''; 10 //alert(subNav.innerHTML); 11 } 12 //鼠標離開菜單,二級菜單動畫收縮起來。 13 aLi[i].onmouseout=function(){ 14 var subNav=this.getElementsByTagName("ul")[0]; 15 subNav.className="subNav"; 16 } 17 } 18 } 19 </script>
1 function getFormatTime(time) { 2 var time = time 0; 3 4 var h = parseInt(time/3600), 5 m = parseInt(time%3600/60), 6 s = parseInt(time%60); 7 h = h < 10 ? "0"+h : h; 8 m = m < 10 ? "0"+m : m; 9 s = s < 10 ? "0"+s : s; 10 11 return h+":"+m+":"+s; 12 }
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 6 <title>Date</title> 7 </head> 8 <body onload="startTime()"> 9 <script> 10 // var date = new Date(); 11 // document.write(date.getFullYear()+"<br />");//年 12 // document.write(date.getMonth()+"<br />"); //月要加1 13 // document.write(date.getDate()+"<br />");//日期 14 // document.write(date.getDay()+"<br />"); //星期 15 // document.write(date.getHours()+"<br />");//時 16 // document.write(date.getMinutes()+"<br />");//分 17 // document.write(date.getSeconds()+"<br />"); //秒 18 19 function startTime() { 20 var today = new Date(); 21 var h = today.getHours(); 22 var m = today.getMinutes(); 23 var s = today.getSeconds(); 24 m = checkTime(m); 25 s = checkTime(s); 26 document.getElementById("timetxt").innerHTML = h+":"+m+":"+s; 27 t = setTimeout(function(){ 28 startTime(); 29 },500); 30 } 31 function checkTime(i){ 32 if(i<10){ 33 i = "0"+i; 34 } 35 return i; 36 } 37 </script> 38 <div id="timetxt"></div> 39 </body> 40 </html>
1 <html> 2 3 <head> 4 <script type="text/javascript"> 5 function upperCase(x) 6 { 7 var y=document.getElementById(x).value 8 document.getElementById(x).value=y.toUpperCase() 9 } 10 </script> 11 </head> 12 13 <body> 14 15 Enter your name: <input type="text" id="fname" onchange="upperCase(this.id)"> 16 17 </body> 18 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <form> 9 Type some text (numbers not allowed): 10 <input type="text" onkeydown="return noNumbers(event)" /> 11 </form> 12 13 <script type="text/javascript"> 14 function noNumbers(e) 15 { 16 var keynum; 17 var keychar; 18 var numcheck; 19 20 if(window.event) // IE 21 { 22 keynum = e.keyCode; 23 } 24 else if(e.which) // Netscape/Firefox/Opera 25 { 26 keynum = e.which 27 } 28 keychar = String.fromCharCode(keynum) 29 numcheck = /\d+/ 30 return !numcheck.test(keychar) //把這個!去掉就是不能限制字母了 31 } 32 </script> 33 </body> 34 </html>
<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>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>一個增刪demo</title> 6 </head> 7 <body> 8 <input type="text" id="text"> 9 <input type="button" value="添加" id="button"> 10 <ul> 11 <li>第1個<button class="btn" id="1">刪除</button></li> 12 <li>第2個<button class="btn" id="2">刪除</button></li> 13 <li>第3個<button class="btn" id="3">刪除</button></li> 14 </ul> 15 <script> 16 var button = document.getElementById("button"); 17 var text = document.getElementById("text"); 18 var ul = document.getElementsByTagName("ul")[0]; 19 var btnClass = document.getElementsByClassName("btn"); 20 button.onclick = function(){ 21 var deleteButton = document.createElement("button"); 22 var value = text.value; 23 deleteButton.setAttribute("class","btn"); 24 var deleteText = document.createTextNode("刪除"); 25 deleteButton.appendChild(deleteText); 26 var li = document.createElement("li"); 27 var liText = document.createTextNode(value); 28 li.appendChild(liText); 29 li.appendChild(deleteButton); 30 ul.appendChild(li); 31 for(var i=0;i<btnClass.length;i++){ 32 btnClass[i].onclick=function(){ 33 this.parentNode.parentNode.removeChild(this.parentNode); 34 } 35 } 36 } 37 38 for(var i=0;i<btnClass.length;i++){ 39 btnClass[i].onclick=function(){ 40 this.parentNode.parentNode.removeChild(this.parentNode); 41 } 42 } 43 </script> 44 </body> 45 </html>
1 <script type="text/javascript"> 2 /*generator實現抽獎邏輯*/ 3 let draw=function(count){ 4 console.info(`剩餘${count}`); 5 } 6 let residue=function* (count){ 7 while(count>0){ 8 count--; 9 yield draw(count); 10 } 11 } 12 13 let star=residue(5); //將Generator實例 14 star.next() 15 star.next() 16 star.next() 17 </script>
//寫出一個比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>
let arr=[2,3,4,2,3]; console.log(arr.filter(function(item,index,self){ return self.indexOf(item)==index} ) )
注:性能差javascript
/*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);
注:性能良好php
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]
注:性能優css
1 let arr=[1,2,3,4,5,3,5,6,2]; 2 let b=[]; 3 let c={}; 4 for(let i=0;i<arr.length;i++){ 5 if(!c[arr[i]]){ 6 b.push(arr[i]); 7 c[arr[i]]='hello'; // 8 } 9 } 10 console.log(b);//[ 1, 2, 3, 4, 5, 6 ] 11 console.log(c); 12 /*{1: "hello", 2: "hello", 3: "hello", 4: "hello", 5: "hello", 6: "hello"}*/
注:性能最優html
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))
注:性能最差vue
[1,2,3,1,'a',1,'a'].filter(function(ele,index,array){ return index===array.indexOf(ele) })
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]
[...new Set('ababbc')].join('') // "abc"
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]); }
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]); } }
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))
1 function showWindowHref(arr){ 2 var sHref = arr; 3 var args = sHref.split('?'); 4 if(args[0] == sHref){ 5 return ""; 6 } 7 var arr = args[1].split('&'); 8 alert(arr) //staffid=12333,name=xiaoming,age=23 9 var obj = {}; 10 for(var i = 0;i< arr.length;i++){ 11 var arg = arr[i].split('='); 12 obj[arg[0]] = arg[1]; 13 console.log(obj[arg[0]]) //12333,xiaomi,23 14 } 15 return obj; 16 } 17 var href = showWindowHref("https://www.runoob.com/jsref/met-win-close.html?staffid=12333&name=xiaoming&age=23"); // obj 18 alert(href['name']); // xiaoming
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原生的Ajax</title> 6 </head> 7 <body> 8 <h1></h1> 9 <script> 10 var xmlhttp; 11 load(); 12 function load(){ 13 if(window.XMLHttpRequest){ 14 xmlhttp=new XMLHttpRequest(); 15 // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼 16 }else { 17 xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); 18 //IE6 5 19 } 20 xmlhttp.onreadystatechange=function(){ 21 if(xmlhttp.readyState===4&&xmlhttp.status===200){ 22 // 0: 請求未初始化 23 // 1: 服務器鏈接已創建 24 // 2: 請求已接收 25 // 3: 請求處理中 26 // 4: 請求已完成,且響應已就緒 27 // 200: "OK" 28 // 404: 未找到頁面 29 //responseText表明字符串形式迴應 responseXML表明XML形式迴應 30 document.getElementsByTagName('h1')[0].innerHTML=xmlhttp.responseText; 31 } 32 }; 33 xmlhttp.open('GET','http://www.wangwei123.cn/xx/public/admin/aside/typelist',true);//TRUE表明異步 34 xmlhttp.send(); 35 } 36 </script> 37 </body> 38 </html>
1 100——客戶必須繼續發出請求 2 101——客戶要求服務器根據請求轉換HTTP協議版本 3 200——交易成功 4 201——提示知道新文件的URL 5 202——接受和處理、但處理未完成 6 203——返回信息不肯定或不完整 7 204——請求收到,但返回信息爲空 8 205——服務器完成了請求,用戶代理必須復位當前已經瀏覽過的文件 9 206——服務器已經完成了部分用戶的GET請求 10 300——請求的資源可在多處獲得 11 301——刪除請求數據 12 302——在其餘地址發現了請求數據 13 303——建議客戶訪問其餘URL或訪問方式 14 304——客戶端已經執行了GET,但文件未變化 15 305——請求的資源必須從服務器指定的地址獲得 16 306——前一版本HTTP中使用的代碼,現行版本中再也不使用 17 307——申明請求的資源臨時性刪除 18 400——錯誤請求,如語法錯誤 19 401——請求受權失敗 20 402——保留有效ChargeTo頭響應 21 403——請求不容許 22 404——沒有發現文件、查詢或URl 23 405——用戶在Request-Line字段定義的方法不容許 24 406——根據用戶發送的Accept拖,請求資源不可訪問 25 407——相似401,用戶必須首先在代理服務器上獲得受權 26 408——客戶端沒有在用戶指定的時間內完成請求 27 409——對當前資源狀態,請求不能完成 28 410——服務器上再也不有此資源且無進一步的參考地址 29 411——服務器拒絕用戶定義的Content-Length屬性請求 30 412——一個或多個請求頭字段在當前請求中錯誤 31 413——請求的資源大於服務器容許的大小 32 414——請求的資源URL長於服務器容許的長度 33 415——請求資源不支持請求項目格式 34 416——請求中包含Range請求頭字段,在當前請求資源範圍內沒有range指示值,請求也不包含If-Range請求頭字段 35 417——服務器不知足請求Expect頭字段指定的指望值,若是是代理服務器,多是下一級服務器不能知足請求 36 500——服務器產生內部錯誤 37 501——服務器不支持請求的函數 38 502——服務器暫時不可用,有時是爲了防止發生系統過載 39 503——服務器過載或暫停維修 40 504——關口過載,服務器使用另外一個關口或服務來響應用戶,等待時間設定值較長 41 505——服務器不支持或拒絕支請求頭中指定的HTTP版本
1 <script type="text/javascript"> 2 window.onload = function() { 3 new Camel('border-bottom-color'); 4 } 5 6 function Camel(str) { 7 this.result = ''; 8 this.arr = str.split('-'); 9 this.result += this.arr[0].toString(); 10 for(var i = 1; i < this.arr.length; i++) { 11 var str1 = this.arr[i].toString(); 12 var str2 = str1.charAt(0).toUpperCase(); 13 var str3 = str2 + str1.slice(1); 14 this.result += str3; 15 } 16 console.log(this.result); //borderBottomColor 17 } 18 </script>
<!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>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{margin:0;padding: 0;} .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: 1; } .checkout-title:before{ position: absolute; content: ''; border-bottom: 1px solid green; width: 100%; top:50%; left: 0; z-index: 0; } /* 居中線製做方法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>
<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的手風琴效果相似java
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>
<!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>
<!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>
<!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)
<!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>
<!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>
<!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>
<!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>
<!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>
concat()
indexOf()
lastIndexOf()
includes()
toString()
slice()
//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 }
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);
var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return 0.5 - Math.random()}); document.getElementById("demo").innerHTML = points; }
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。
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"]`
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>md轉換爲html</title> 7 <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script> 8 </head> 9 10 <body> 11 <div style="font-size: 20px;height: 30px; text-align: center;color: #009689; font-weight: bold;">Markdown轉換爲HTML的Demo</div> 12 <style> 13 .markdown-here-wrapper { 14 font-size: 16px; 15 line-height: 1.8em; 16 letter-spacing: 0.1em; 17 } 18 19 pre, 20 code { 21 font-size: 14px; 22 font-family: Roboto, 'Courier New', Consolas, Inconsolata, Courier, monospace; 23 margin: auto 5px; 24 } 25 26 code { 27 white-space: pre-wrap; 28 border-radius: 2px; 29 display: inline; 30 } 31 32 pre { 33 font-size: 15px; 34 line-height: 1.4em; 35 display: block; 36 !important; 37 } 38 39 pre code { 40 white-space: pre; 41 overflow: auto; 42 border-radius: 3px; 43 padding: 1px 1px; 44 display: block !important; 45 } 46 47 strong, 48 b { 49 color: #BF360C; 50 } 51 52 em, 53 i { 54 color: #009688; 55 } 56 57 hr { 58 border: 1px solid #BF360C; 59 margin: 1.5em auto; 60 } 61 62 p { 63 margin: 1.5em 5px !important; 64 } 65 66 table, 67 pre, 68 dl, 69 blockquote, 70 q, 71 ul, 72 ol { 73 margin: 10px 5px; 74 } 75 76 ul, 77 ol { 78 padding-left: 15px; 79 } 80 81 li { 82 margin: 10px; 83 } 84 85 li p { 86 margin: 10px 0 !important; 87 } 88 89 ul ul, 90 ul ol, 91 ol ul, 92 ol ol { 93 margin: 0; 94 padding-left: 10px; 95 } 96 97 ul { 98 list-style-type: circle; 99 } 100 101 dl { 102 padding: 0; 103 } 104 105 dl dt { 106 font-size: 1em; 107 font-weight: bold; 108 font-style: italic; 109 } 110 111 dl dd { 112 margin: 0 0 10px; 113 padding: 0 10px; 114 } 115 116 blockquote, 117 q { 118 border-left: 2px solid #009688; 119 padding: 0 10px; 120 color: #777; 121 quotes: none; 122 margin-left: 1em; 123 } 124 125 blockquote::before, 126 blockquote::after, 127 q::before, 128 q::after { 129 content: none; 130 } 131 132 h1, 133 h2, 134 h3, 135 h4, 136 h5, 137 h6 { 138 margin: 20px 0 10px; 139 padding: 0; 140 font-style: bold !important; 141 color: #009688 !important; 142 text-align: center !important; 143 margin: 1.5em 5px !important; 144 padding: 0.5em 1em !important; 145 } 146 147 h1 { 148 font-size: 24px !important; 149 border-bottom: 1px solid #ddd !important; 150 } 151 152 h2 { 153 font-size: 20px !important; 154 border-bottom: 1px solid #eee !important; 155 } 156 157 h3 { 158 font-size: 18px; 159 } 160 161 h4 { 162 font-size: 16px; 163 } 164 165 166 table { 167 padding: 0; 168 border-collapse: collapse; 169 border-spacing: 0; 170 font-size: 1em; 171 font: inherit; 172 border: 0; 173 margin: 0 auto; 174 } 175 176 tbody { 177 margin: 0; 178 padding: 0; 179 border: 0; 180 } 181 182 table tr { 183 border: 0; 184 border-top: 1px solid #CCC; 185 background-color: white; 186 margin: 0; 187 padding: 0; 188 } 189 190 table tr:nth-child(2n) { 191 background-color: #F8F8F8; 192 } 193 194 table tr th, 195 table tr td { 196 font-size: 16px; 197 border: 1px solid #CCC; 198 margin: 0; 199 padding: 5px 10px; 200 } 201 202 table tr th { 203 font-weight: bold; 204 color: #eee; 205 border: 1px solid #009688; 206 background-color: #009688; 207 } 208 </style> 209 <style> 210 #area>table { 211 width: 100%; 212 table-layout: fixed; 213 } 214 215 #area table tr td { 216 margin: 0; 217 padding: 6px; 218 border: 0; 219 220 } 221 222 223 #md-area { 224 225 width: 100%; 226 height: 600px; 227 font-size: 18px; 228 overflow: hidden; 229 font-weight: bold; 230 outline: none; 231 } 232 233 #show-area { 234 height: 600px; 235 background-color: #FCF6E5; 236 } 237 238 .clearfix:before { 239 content: ""; 240 display: table; 241 } 242 </style> 243 <script> 244 function mdSwitch() { 245 var mdValue = document.getElementById("md-area").value; 246 var converter = new showdown.Converter(); 247 var html = converter.makeHtml(mdValue); 248 document.getElementById("show-area").innerHTML = html; 249 } 250 </script> 251 <div id="area"> 252 <table> 253 <tr> 254 <td><textarea name="" id="md-area" onkeyup=mdSwitch()></textarea></td> 255 <td> 256 <div id="show-area" class="clearfix"></div> 257 </td> 258 </tr> 259 </table> 260 </div> 261 </body> 262 263 </html>
<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] + "  "+ infos[i][3]+"</br>"); } } //第二次篩選,找出都是女生的信息 </script>
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>加減乘除計算器</title> 5 <script type="text/javascript"> 6 function count(){ 7 8 //獲取第一個輸入框的值 9 var a=document.getElementById("txt1").value; 10 //獲取第二個輸入框的值 11 var b=document.getElementById("txt2").value; 12 //獲取選擇框的值 13 var c=document.getElementById("select").value; 14 var sum=""; 15 switch(c) 16 { 17 case '+': 18 sum=parseFloat(a) + parseFloat(b); 19 break; 20 case '-': 21 sum=parseFloat(a) - parseFloat(b); 22 break; 23 case '*': 24 sum=parseFloat(a) * parseFloat(b); 25 break; 26 default: 27 sum=parseFloat(a) / parseFloat(b); 28 break; 29 30 } 31 document.getElementById("fruit").value=sum; 32 } 33 </script> 34 </head> 35 <body> 36 <input type='text' id='txt1' /> 37 <select id='select'> 38 <option value='+'>+</option> 39 <option value="-">-</option> 40 <option value="*">*</option> 41 <option value="/">/</option> 42 </select> 43 <input type='text' id='txt2' /> 44 <input type='button' value=' = ' onclick="count()" /> <!--經過 = 按鈕來調用建立的函數,獲得結果--> 45 <input type='text' id='fruit' /> 46 </body> 47 </html>
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()
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]
待續......node