JavaScript技巧精粹
阅读Eloquent JavaScript提高JavaScript技能:https://eloquentjavascript.net/ #生活技巧# #工作学习技巧# #编程学习资源#
<meta charset = "utf-8">
<script>
var colorText = "red,blue,green,yellow";
var one = colorText.split(",");
var two = colorText.split(",", 2);
var thr = colorText.split(/[^\,]+/)
console.log(one);
console.log(two);
console.log(thr);
function htmlEscape(text) {
return text.replace(/[<>"&]/g, function(match, pos, originalText) {
switch(match) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
console.log(htmlEscape("<p class = \"greeting\">Hello World !</p>"));
var text = "cat, bat, sat, fat";
result = text.replace(/(.at)/g, "word ($1)");//匹配第一個字符串捕獲組
console.log(result)
var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
console.log(result);
result = text.replace(/at/g, "Rui");
console.log(result);
var text = "cat, bat, sat, fat"
var pos = text.search(/at/);
console.log(pos);
var text = "cat , bat , sat , fat";
var pattern = /.at/;
//與pattern.exec(text)
var matches = text.match(pattern);
console.log(matches.index);
console.log(matches[0]);
console.log(pattern.lastIndex);
var sV = "hello world";
console.log(sV.toLocaleUpperCase());
console.log(sV.toUpperCase());
console.log(sV.toLocaleLowerCase());
console.log(sV.toLowerCase());
var sV = " Hello World ";
var one = sV.trim();
console.log(one);
var sV = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = sV.indexOf("e");
while(pos > -1) {
positions.push(pos);
pos = sV.indexOf("e", pos + 1);
}
console.log(positions);
var sV = "Hello World"
console.log(sV.indexOf("o"));
console.log(sV.lastIndexOf("o"));
console.log(sV.indexOf("o",6));
console.log(sV.lastIndexOf("o",6));
var sV = "Hello World";
console.log(sV.slice(-3));//11-3 =8
console.log(sV.substring(-3));//=0
console.log(sV.substr(-3));
console.log(sV.slice(3,-4));
console.log(sV.substring(3,-4));//等於3,0,小的排前,所以0,3
console.log(sV.substr(3,-4));
var stringValue = "hello World"
console.log(stringValue.charAt(1));
console.log(stringValue.charCodeAt(1))
console.log(stringValue[0])
var stringValue = "hello ";
var result = stringValue.concat("World" + " !");
console.log(result);
var stringValue = "Hello World";
console.log(stringValue.slice(3));
console.log(stringValue.substring(3));
console.log(stringValue.substr(3));
console.log(stringValue.slice(3,8));
console.log(stringValue.substring(3,8));
console.log(stringValue.substr(2,7));
var stringObject = new String("hello world");
console.log(stringObject)
var stringValue = "Hello World";
console.log(stringValue.length);
var numberObject = new Number(10); 創建number對象 的實例
var numberValue = 10;
console.log(typeof numberObject);
console.log(typeof numberValue);
console.log(numberObject instanceof Number);
console.log(numberValue instanceof Number);
var number = new Number(10);
//console.log(number)
var num = 10;
console.log(num.toFixed(2));
var num = 10.005;
console.log(num.toFixed(2));
var num = 10;
console.log(num.toExponential(1));
var num = 123.4567890;
console.log(num.toPrecision(5));
console.log(num.toPrecision(2));
var falseObject = new Boolean(false);
var result = falseObject && true;
console.log(falseObject instanceof Boolean);
console.log(result);
var falseValue = false;
result = falseValue && true;
console.log(falseValue instanceof Boolean)
console.log(result);
var booleanObject = new Boolean(true);
console.log(typeof booleanObeject)
var value = "25"
var number = Number(value);//轉型函數
console.log(typeof number);number
var obj = new Number(value);
console.log(typeof obj);//對象
var obj = new Object("some text");
console.log(obj instanceof String);
//基本包裝類型、執行瞬間刪除
var s1 = "some text";
s1.color = "yellow";
console.log(s1.color);
var s1 = "some text";
var s2 = s1.substring(2);
console.log(s2)
//過程,後臺處理~
var s1 = new String("some text");
var s2 = s1.substring(2);
s1 = null;
console.log(s2);
color = "red";
var r = {color:"yellow"};
function sayColor() {
console.log(this.color);
}
var one = sayColor.bind(r);//創建一個one函數實例,把其 this 通過bind 綁定到r對象。
one()
window.color = "yellow";
var r = {color: "blue"};
function sayColor() {
console.log(this.color);
}
//更下面等價
sayColor.call(r)
//更下面等價
r.sayColor = sayColor;
r.sayColor();
//call 方法
function sum(num1, num2) {
return num1 + num2;
}
function callSum(num1, num2) {
return sum.call(this, num1, num2);
}
console.log(callSum(10, 10))
//apply 方法
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(num1, num2) {
return sum.apply(this, arguments);//apply 2參數,1是其運行函數的作用域,2是參數數組。
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2]);
}
console.log(callSum1(10, 10));
console.log(callSum2(10, 10))
//函數的 length 屬性
function sayName(name) {
console.log(name)
}
function sum(num1, num2) {
return num1 + num2;
}
function sayHi() {
console.log("hi");
}
console.log(sayName.length);
console.log(sum.length);
console.log(sayHi.length);
//caller 可記住 “開燈的人”
function outer() {
inner();
}
function inner() {
//alert(inner.caller);
console.log(arguments.callee.caller);
}
outer();
//this 對象
window.color = "red";
var o = {color: "blue"};
function sayColor() {
console.log(this.color);
}
o.sayColor = sayColor;
o.sayColor()
function factorial(num) {
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num-1);
}
}
console.log(factorial(2));
//函數中返回另一個函數
function createComparionFunction(onename) {
return function(object1, object2) {
var value1 = object1[onename];
var value2 = object2[onename];
if (value1 < value2) {
return -1;
} else if(value1 > value2) {
return 1;
} else {
return 0;
}
}
}
var data = [{name:"Rui",age:28},{name:"Hong",age:20}]
data.sort(createComparionFunction("name"));
console.log(data[0].name);
data.sort(createComparionFunction("age"));
console.log(data[0].age);
//函數中運用函數!
function Rui(someFunction, someArgument) {
return someFunction(someArgument);
}
function add10(num) {
return num + 10;
}
var resule = Rui(add10, 10);
console.log(resule)
function getGreeting(name) {
return "hello, " + name;
}
var whoName = Rui(getGreeting, 'Papa');
console.log(whoName);
//無函數聲明,不可能比先運行,
console.log(rui(0));
var rui = function(num){
return num;
}
//可執行。
alert(rui(1));
function rui(num) {
return num
}
function add(num) {
return num + 100;
}
function add(num) {
return num + 200;
}
console.log(add(200));
var rui = function(num) {
return num + 1;
}
rui = function(num) {
return num + 2;
}
console.log(rui(0))
var text = "this has been a short summer.";
var pattern = /(..)or(.)/g;
if (pattern.test(text)) {
console.log(RegExp.$1);
console.log(RegExp.$2);
console.log(RegExp.$3);
console.log(RegExp.$4);
console.log(RegExp.$5);
console.log(RegExp.$6);
console.log(RegExp.$7);
console.log(RegExp.$8);
console.log(RegExp.$9);
}
var text = "this has been a short summer"
var pattern = /(.)hort/g;
if (pattern.test(text)) {
console.log(RegExp.$_);
console.log(RegExp["$`"]);
console.log(RegExp["$'"]);
console.log(RegExp["$&"]);
console.log(RegExp["$+"]);
console.log(RegExp["$*"]);
}
//RegExp 構造函數 屬性!
var text = "this has been a short summer"
var pattern = /(.)hort/g;
if (pattern.test(text)) {
console.log(RegExp.input);
console.log(RegExp.leftContext);
console.log(RegExp.rightContext);
console.log(RegExp.lastMatch);
console.log(RegExp.lastParen);
console.log(RegExp.multiline)
}
var text = new RegExp("\\[bc\\]at","gi");
one = text.toString();
one = text.toLocaleString()
one = text.valueOf
console.log(one)
var text = "000-00-0000"
var one = /\d{3}-\d{2}-\d{4}/;
if (one.test(text)){
console.log("U Can")
}
console.log(one);
//全局和局部exec()的區別。。局部只會返回第一位
var text = "cat,bat,sat,fat";
var one = /.at/;
var go = one.exec(text);//"cat"
goo = go.index;//"0"
goo = go[0]//"cat"
goo = one.lastIndex;//"0"
//console.log(goo);
var two = /.at/g;//at結尾的3位數
var texttwo = two.exec(text);
go = texttwo.index;
go = texttwo[0];
go = two.lastIndex;
go = texttwo = two.exec(text);
go = texttwo.index;
go = texttwo[0];
go = two.lastIndex;
console.log(go);
var text = "mom and dad and baby";
var find = /mom( and dad (and baby)?)?/gi;
var go = find.exec(text)
goo = go.index
goo = go.input
goo = go[0]
goo = go[1]
goo = go[2]
goo = go[3]
console.log(goo);
var one = /\[bc\]at/i;
go = one.global;
go = one.ignoreCase;
go = one.lastIndex;
go = one.multiline;
go = one.source;//"\[bc\]at"
console.log(go);
var two = new RegExp("\\[bc\\]at","i");
goo = two.global;
goo = two.ignoreCase;
goo = two.lastIndex;
goo = two.multiline;
goo = two.source;
console.log(goo);
//正則表達式
var one = /[bc]at/i;//匹配第一個 bat和cat,不區分大小
var one = /\[bc\]/i;//匹配第一個 【bat】或【cat】,不區分大小
var one = /.at/i;//匹配所有以"at"結尾的3個字符的組合,不區分大小
var one = /\.at/gi; //匹配所有".at",不區分大小
var one = /[bc]at/i;//匹配第一個‘bat’或‘cat’ 不區分大小
var two = new RegExp("[bc]at","i")//與one樓上相同的,使用構造函數創建
console.log(two)
var re = null,
i;
for (i = 0; i < 10; i++) {
re = /cat/g;
re.test("catastrophe");
}
console.log(one)
時間
var times = new Date();
var a = times;
time = times.toDateString()
time = times.toTimeString()
time = times.toLocaleString()
time = times.toLocaleDateString()
time = times.toLocaleTimeString()
time = times.toUTCString()
time = times.toGMTString()
time = times.getTime()
//time = a.setTime()
time = a.getFullYear()
time = a.getUTCFullYear()
//time = a.setFullYear();
time = a.getMonth()
time = a.getUTCMonth()
time = a.getTime()
console.log(time)
var a = new Date(Date.parse("5/19/2017"))
console.log(a)
//迭代!
var numbers = [1,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array){
return (item > 2);
})
console.log(everyResult);
var someResult = numbers.some(function(item,index,array){
return (item > 2);
})
console.log(someResult);
var filterResult = numbers.filter(function(item,index,array){
return (item > 2);
})
console.log(filterResult);
var mapResult = numbers.map(function(item,index,array){
return item * 2;
})
console.log(mapResult
)
var reduceResult = numbers.reduce(function(prev,cur,index,array){
return prev + cur;
})
console.log(reduceResult)
var number = [1,10,2,5];
var reduceRight = number.reduceRight(function(prev,cur,index,array){
return prev + cur;
})
console.log(reduceRight)
var person = {name: "Nicholas"};
var people = [{name: "Nicholas"}];
var morePeople = [person];
console.log(people.indexOf(person));
console.log(morePeople.indexOf(person))
var number = [1,2,3,4,5,4,3,2,1];
console.log(number.indexOf(4))
console.log(number.lastIndexOf(4))
console.log(number.indexOf(4,4));
console.log(number.lastIndexOf(4,4))
//splice() 連接~
var color = ["yellow","blue","red"];//新建數組
var removed = color.splice(0,1);//刪除 0 下標位置的項,數量1
removed = color.splice(1,0,["value1"],["value2"]);
removed = color.splice(2,1,["value3"],["value4"]);
console.log(removed);//返回的數組中只包含一項;
console.log(color)
//slice() 切割
var color = ["red","green","blue","yellow","black"]
var colors = color.slice(1);
var colors2 = color.slice(2,4);
console.log(colors)
console.log(colors2)
var colors = ["red",'green','yellow'];
var colors2 = colors.concat("black",["blue",true]);
var color = colors.concat();
console.log(color)
//比較函數
function compare(value1, value2) {
if (value1 < value2) {
return -1;
}else if(value1 > value2) {
return 1;
}else {
return 0;
}
}
//更簡單的比較函數
function compare1(value1, value2) {
return value2 - value1;
}
var values = [0, 1, 5, 10, 15, 20];
values.sort(compare1);
console.log(values);
//隊列方法 shift()
var one = [];
one.push("yellow","red")
one[2] = "black"
one = one.shift();
console.log(one)
var colors = new Array();
var count = colors.unshift("yellow","red");
count = colors.unshift("black");
var item = colors.pop();
console.log(item)
console.log(count)
console.log(colors)
//這些 數組可以看成 棧!
var colors = new Array();
var count = colors.push("red","blue")
count = colors.push("yellow")
var item = colors.pop();
console.log(colors.length)
console.log(colors)
var p1 = {
toLocaleString : function() {
return "one";
},
toLocaleString : function() {
return "two";
}
};
var p2 = {
toString : function() {
return "one";
},
toString : function() {
return "two";
}
};
var p = [p1,p2];
alert (p)
alert (p.toString());
alert (p.toLocaleString())
console.log(p)
function displayInfo(args) {
var output = "";
if (typeof args.name == "string"){
output += "Name: " + args.name + "\n";
}
if (typeof args.age == "number") {
output += "age: " + args.age + "\n";
}
alert(output);
}
displayInfo({
name: "nicholas",
age: 18
});
displayInfo ({
name: "Greg"
});
var o = {x:"one", y:"two"};
a = delete o.x;
a = typeof o.x;
a = delete o.x;
a = delete o;
a = delete 1;
a = this.x = 1;
a = delete x;
a = x
console.log(a)
var geval = eval;//使用別名調用 eval 將是全局 eval
var x = "global", y = "global";
function f() {
var x = "local";
eval("x += 'changed';");
return x;
}
console.log(f())
function g() {
var y = "local";
geval("y += 'changed';");//調用改變了全局變量的值
return y;
}
console.log(g());
a = eval("3+2")
console.log(a)
//屬性訪問表達式
var o = {x:1, y:{z:3}};
var a = [o,4,[5,6]];
b = o.x
b = o.y.z
b = o[0]
b = o["x"]
b = a[1];
b = a["1"];
b = a[1];
b = o[0]
b = a[2]["1"]
b = a[2][0]
b = a[0].x
console.log(b);
function createperson(name) {
var localperson = new Object();
localperson.name = name;
return localperson;
}
var globalPerson = createperson("Nicholas");
//手工解除 globalPerson的引用;
globalPerson = null;
console.log(globalPerson)
var element = document.getElementById("some_element");
var myObject = new Object();
myObject.element = element;
element.someObject = myObject;
//結果會返回color,搜索過程從作用域的前端開始,
//向上逐級查詢給定名字匹配的標識符。
var color = "blue";
function getColor() {
return color;
}
console.log(getColor());
// JS 中 if 語句中的變量聲明會將變量添加到當前的執行環境。
if (true) {
var color = "bule";
}
console.log(color);
function buildUrl() {
var qs = "?debug=true";
with (location) {
var url = href + qs;
}
return url;
}
console.log(buildUrl());
//作用域鏈
var color = "blue";
function changeColor() {
var anotherColor = "red";
function swapColors() {
var tempColor = anotherColor;//創建一個變量;
anotherColor = color;//可以訪問 anotherColor
color = tempColor;//可以訪問color
//可以訪問其他兩個環境是因為是它的父執行環境
}
swapColors();
}
changeColor();
var color = "blue";
function changeColor() {
if (color === "blue") {
color = "red";
return color;
}else {
color = "blue";
return color;
}
}
console.log(changeColor())
var a = /come on/g;
b = typeof a;
console.log(b);
var one = "one";//刪不了!聲明的全局不發刪!
two = "two";
this.thr = "thr";
delete two;
delete thr;
delete one;
console.log(one);
var o = "object";
function test(o) {
var i = 0;
if (typeof o == "object") {
var j = 0;
for (var k = 0; l < 10; k++) {
console.log(k);
}
console.log(k)
}
console.log(j);
}
console.log(test(o))
var scope = "global scope";
function checkscope() {
var scope = "local scope";
function nested() {
var scope = "nested scope";
return scope;
}
return scope;
}
console.log(checkscope());
var scope = "global";
function checkscope() {
var scope = "local"
return scope;
}
console.log(checkscope());
for (i = 0,j = 10; i < 10; i++, j--){
console.log(i * j);
}
for (i in 0){
console.log(i)
}
var n = 123456.789
a = n.toPrecision(1);
var b = new Date();
a = typeof(b + 1)
a = typeof(b - 1)
a = typeof(b / 1)
a = typeof(b % 1)
a = typeof(b * 1)
a = (b == b.toString())
a = typeof(b > (b-1))
console.log(a)
a = Object(3);
a = 10 + ""
a = + "2312"// Number(a)
a = typeof (a)
var b = 17
a = "0" + b.toString(8);
console.log(a)
//比較2個單獨的數組或對象是否 相等
function rui(a,b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++){
if (a[i] !== b[i]) return false;
}
return true;
}
var a = {x:1};
a.x = 2;
a.y = 3;
console.log(a.value)
//字符串無法更改的..你所更改的其實是創建的一個新的。
var s = "hello";
b = s.toUpperCase();
console.log(s)
console.log(b)
var text = "testing: 1, 2, 3";
var pattern = /\d+/g
a = pattern.test(text)
a = text.search(pattern);
a = text.match(pattern)
a = text.replace(pattern, "#")
a = text.split(/\D+/)
console.log(a)
var a = "\b"
a = "\o"
a = "\t"
a = "\n"
a = "\v"
a = "\f"
a = "\r"
a = "\'"
console.log(a)
var a =
"easdasd\
asdasd\
asdasd\
asdasd"
document.write(a)
console.log(a)
var a = new Date(2011, 0, 1);
a = new Date(2017, 5, 16, 15, 55,30);
b = new Date();
a = b.getFullYear();
a = b.getMonth();
a = b.getDate()
a = b.getTime()
a = b.getDay()
a = b.getHours()
a = b.getUTCHours()
console.log(a)
function rui() {
a = arguments[0] + arguments[1];
return a;
alert(a);//不會執行..
}
console.log(rui('haha' , "xixi"));
//switch 語句
var a = 50;
switch(a) {
case (a = 20):
alert("yes.U Can.");
break;
case ("a = 40 or 50"):
alert("yes.U Can.");
break;
default:
alert("yes.U Can3.");
}
//可以字符串、變量、表達式——case的值
switch("hello world"){
case "hello" + " world":
alert("what?");
break;
case "goodBye":
alert("U Can.");
break;
default:
alert("Yes..U Can..");
}
if (i == 25) {
alert("aaha");
}else if (i == 30) {
alert("asd");
}else if (i == 35){
alert("sad");
}else{
alert("fuck")
}
var i = 5;
switch(i) {
case 25:
alert("what?");
break;
case 30:
alert("aha");
break;
case 35:
alert("asdasd>");
break;
default:
alert("fuck you")
}
var a = 0;
for (var i = 1;i < 10; i++) {
if (i % 5 == 0){
break;
}
a++;
}
console.log(a);
var b = 0;
for (var i = 1;i < 10; i++) {
if (i % 5 == 0) {
continue;
}
b++;
}
console.log(b);
var a = 10
for (var i = 0; i < 10; i++){
//
}
alert(i);
//全等/不全等
var a = (NaN === NaN)
a = null == undefined
console.log(a);
//減法
var a = 10 - 5;
a = NaN - 5;
a = 10 - NaN;
a = Infinity - Infinity;
a = -Infinity - -Infinity;
a = Infinity - -Infinity;
a = -Infinity - Infinity;
a = +0 - +0;
a = +0 - +0;
a = -0 - +0;
console.log(a);
var a = 1 + 2;
a = NaN + 1
a = +0 + -0;
b = 5;
c = 10
a = "I Can.." + b + c
a = "I can.." + (b + c);
console.log(a)
//求模
var a = 26 % 5;
a = Infinity % 5
a = 123 % 0
a = Infinity % Infinity;
a = 100 % Infinity
a = 0 % 100
a = true % 6
console.log(a);
var a = 0/0
a = 21021/0
a = Infinity / 2101201201
console.log(a);
//邏輯非~
var a = (!Object);
a = (!"");
a = (!"asda");
a = (!0);
a = (!"25csaz-=");
a = !null;
a = !false;
a = !undefined;
//邏輯與
var q = false;
a = (q && w);
console.log(a);
var myObject = a`Object || bObject;//本章經常使用此種模式-程序的賦值語句
var b = -2;
b.toString(2);
a = b << 5;
console.log(a);
c = a >> 5;
console.log(c);
d = a >>> 5;
console.log(d);
var a = 25 & 6;//與
console.log(a);
a = 25 | 6;//或
console.log(a);
a = 25 ^ 3;//異或
console.log(a);
var a = 25;
b = ~a;//按位非操作符
console.log(a);
console.log(b);//操作數的負值 - 1;
a = -18;
console.log(a.toString(2));
var a = "01";
b = +a;
a = "1.1";
b = +a;
a = "z";
b = +a;
a = false;
b = +a;
a = 1.1;
b = +a;
a = {
valueOf: function() {
return -1;
}
}
b = +a;
console.log(b);
// 會自動轉換
var a = "12312";
++a;
a = "asdb";
++a;
a = false;
++a;
a = true;
++a;
a = "0.212";
++a;
a = "0.12";
--a;
a = new Object();
++a;
console.log(a);
var a = new Object();
a.valueOf();
console.log(a);
var a = "This is the letter sigma: \u03a3."
console.log(a);
var a = "123213asdv"//字母將不會錄入(整數)
a = "100.001.123"//只對第一個‘.’有效;
a = "0xA";//16進制始終會被轉換為0;
a = "070";//始終忽略前導的零;(於parseInt 的第二個區別)
a = "abs";//NaN
a = "3.213e10"//e表示法32130000000
console.log(parseFloat(a));
var a = "060";
b = Number(a); //number 是忽略掉前面的0的,除非是 0x
c = parseInt(a,8);
console.log(b);
var a = parseInt("1 2345asdasd");
a = parseInt(".21321");
a = parseInt(" ");
a = parseInt("0xf");
a = parseInt("22.1231312");
a = parseInt("00021231230");
console.log(a);
var a = "abc"
a = "0.5212412"
a = 1.4232
a = true
a = false
a = "0xfa4b"
a = (ha = null)
console.log(Number(a));
var message = 'hello world!'
if (message) {
alert("value is true.")
}
//只有在缺少分號就無法正確解析代碼的時候,JS才會自動填補分號。
var a
a
=
5
console.log(a);
//用Jquery 編寫的 debug 函數~
function debug(msg) {
var log = $("#debuglog");
if (log.length == 0) {
log = $("<div id = 'debuglog'><h1>Debug Log</h1></div>");
log.appendTo(document.body);
}
}
[!
<meta charset = "utf-8">
<script>
//在document 中的一個指定的區域輸出調試信息
//如果document 不存在這樣一個區域,則創建一個
function debug(msg) {
//通過查看HTML 元素 id 屬性來查找文檔的調試部分
var log = document.getElementById("debuglog");
//如果這個元素不存在,那麼創建一個
if (!log) {
log = document.createElement("div");//創建一個新的 <div>元素
log.id = "debuglog";//給此元素的 ID 賦值
log.innerHTML = "<h1> Debug Log </h1>";//給此元素初始內容
document.body.appendChild(log);//把這個元素添加到文檔末
}
//將消息包裝在 <pre> 中,並添加到 log 中
var pre = document.createElement("pre");//創建 <pre> 標籤
var text = document.createTextNode(msg);//將msg 包裝在以文本節點中
pre.appendChild(text);//文本添加到 pre
log.appendChild(pre);
}
function hide(e, reflow) {//通過 JavaScript 操縱樣式來隱藏元素 e
if (reflow) {//如果 reflow(第二個參數)是 true
e.style.display = "none";//隱藏這個元素,所占空間消失
}else {
e.style.visibility = "hidden";//將e隱藏,保留其所占空間
}
}
function highlight(e) {//通過設置 css類 來高亮顯示e
//簡單的定義或追加 HTML類 屬性
//假設 CSS 樣式表中已有 ‘hilite’類
if (!e.className)e.className = "hilite";
else e.className += "hilite";
}
</script>
Hello
<button onclick = "hide(this); debug('hide button 1');">Hide1</button>
<button onclick = "hide(this, true); debug('hide button 2');">Hide2</button>
!]
//在document 中的一個指定的區域輸出調試信息
//如果document 不存在這樣一個區域,則創建一個
function debug(msg) {
//通過查看HTML 元素 id 屬性來查找文檔的調試部分
var log = document.getElementById("debuglog");
//如果這個元素不存在,那麼創建一個
if (!log) {
log = document.createElement("div");//創建一個新的 <div>元素
log.id = "debuglog";//給此元素的 ID 賦值
log.innerHTML = "<h1> Debug Log </h1>";//給此元素初始內容
document.body.appendChild(log);//把這個元素添加到文檔末
}
//將消息包裝在 <pre> 中,並添加到 log 中
var pre = document.createElement("pre");//創建 <pre> 標籤
var text = document.createTextNode(msg);//將msg 包裝在以文本節點中
pre.appendChild(text);//文本添加到 pre
log.appendChild(pre);
}
function moveon() {
//通過彈出一個對話框來詢問用戶一個問題?
var answer = confirm("Are you ready? ");
//單擊‘確認’按鈕,瀏覽器會加載一個新頁面
if (answer) window.location = "http://luckyman.xyz";
}
//在一分鐘(6W毫秒) 後執行定義的這個函數
setTimeout(moveon, 5000);
//定義一個 構造函數 以初始化一個新的 Point對象
function Point(x, y) {//照慣例, 構造函數均以大寫字母開始
this.x = x;//關鍵字 this 指代初始化的實例
this.y = y;//將函數參數存儲為對象的屬性
}
//使用 new 關鍵字 和 構造函數 來創建一個實例
var p = new Point(1, 1);//平面幾何中的點(1,1)
//通過給構造函數的 prototype 對象賦值給 Point 對象定義方法
Point.prototype.r = function() {
return Math.sqrt(
this.x * this.x +//返回 x2 + y2 的平方根
this.y * this.y//this 指代 調用這個方法的對象
);
}
//Point的實力對象p (以及所有的Point 實例對象)繼承了方法 r()
console.log(p.r());
//for 循環的 階乘
function factorial2(n){
var i, product = 1;
for (i = 5; i <= n; i++)
product *= i;
return product;
}
console.log(factorial2(10));
//絕對值
function abs(x) {
if (x > 0) {
return x;
}else {
return -x;
}
}
console.log(abs(-2));
//階乘
function factorial(n) {
var product = 1;
while (n > 1) {
product *= n;
n--;
}
return product;
}
console.log(factorial(10));
var a = [];
a.push(1,2,3);
a.reverse();//反轉
console.log(a);
points.dist = function(){
var p1 = this[0];
var p2 = this[1];
var a = p2.x - p1.x;
var b = p2.y - p1.y;
return Math.sqrt(a * a + b * b);
}
points.dist();
function rui(x) {
return x + 1;
}
function Rui(x) {
return x * x;
}
console.log(Rui(rui(5)));
var x = 2, y = 3, a;
a = (x == y);
a = (x != y);
a = (x < y);
a = (x <= y);
a = (x > y);
a = (x >= y);
a = ("two" == "three");
a = ("two" > "thrr");
a = (false == (x > y));
a = ((x == 2) && (y == 3));
a = ((x > 3) || (y < 3));
a = (!(x == y));
console.log(a);
</script>
javascript
网址:JavaScript技巧精粹 https://www.yuejiaxmz.com/news/view/1350745
相关内容
JavaScript学习指南:从入门到精通,掌握核心技巧与实践方法26 个写高效干净JavaScript 的小技巧
全面掌握JavaScript编程技巧,从入门到精通的JS使用教程助你快速提升开发能力
JavaScript 实用技巧:提高开发效率与代码质量
15个每位开发者都应该知道的JavaScript性能优化技巧
有个开发者总结这 15 优雅的 JavaScript 个技巧
自动化技术:用JavaScript打造轻松生活
JavaScript学习总结(十三)——极简主义法编写JavaScript类
JavaScript常用优化分享(三)
JavaScript作用域