Home > Article > Web Front-end > The first chapters 1~3 of "JavaScript Classic Examples" (Collection)
Each section of "JavaScript Classic Examples" has detailed code examples, solving problems we often encounter, and giving techniques for building Web applications in any browser. If these codes are helpful to you, just paste them. You can complete the work quickly and learn a lot about JavaScript in the process.
There are 5 basic types: string, numerical value, Boolean value, null, and undefined. There are 3 corresponding constructor objects: string, Number, Boolean
Basic type variables are strictly equal to words literal values, while object instances do not, because primitive types are compared by value, and values are literals
var num1 = 123;var num2 = new Number(123); console.log(typeof num1); //number console.log(typeof num2); //object
Before extraction:This is a list of items: cherries, limes, oranges, apples.
After extraction:[' cherries','limes','oranges','apples']
##indexOf() method can return a specified string value in The position of the first occurrence in the string.
substring() method is used to extract the characters between two specified subscripts in the string.
split() method is used to split a string into an array of strings.
var sentence = 'This is one sentence. This is a sentence with a list of items: cherries, oranges, apples, bananas. That was the list of items.';var start = sentence.indexOf(':');var end = sentence.indexOf('.', start+1);var listStr = sentence.substring(start+1, end);var fruits = listStr.split(','); console.log(fruits); //[" cherries", " oranges", " apples", " bananas"]//取出空格等fruits.forEach(function(elmnt,indx,arry) { arry[indx] = elmnt.trim(); }); console.log(fruits); //["cherries", "oranges", "apples", "bananas"]1.3 Check for an existing, non-empty string
if(typeof unknowVariable === 'string' && unknowVariable.length > 0) {...}1.4 Inserting special characters
backslash (\)
regular expression
replace() method uses Used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
Match | Example | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Matches the beginning of the input | /^This/ Matches This is… | |||||||||||||||
/ Matches This is the end | ||||||||||||||||
Match 0 or more times | /se*/ Matches s seeee or se | |||||||||||||||
Match 0 times or 1 time | /ap?/ Match apple and and | |||||||||||||||
Match 1 or more times | /ap / matches apple but does not match and | |||||||||||||||
strictly matches n times | /ap{2}/strictly Matches apple but does not match apie | ##{n,} | ||||||||||||||
/ap{2,}/ matches apple p, but does not match p | ##{n,m} | |||||||||||||||
/ap{2,4}/ matches 4 p | /a.e/ in apppppple matches ape and axe[…] | Any characters in square brackets|||||||||||||||
[^…] | Any character except square brackets | |||||||||||||||
\b | matches word boundaries | |||||||||||||||
\B | matches a non-word boundary | |||||||||||||||
\d | number in nono from 0 to 9 | |||||||||||||||
\D | matches any non-numeric character | |||||||||||||||
##\w | Matches any word characters (letters, arrays and underscores | |||||||||||||||
# in javaScript | ##\WMatches any non-word characters (non-letters, arrays and underscores) | /\W/ matches % | ||||||||||||||
#\n | Matches a newline | |||||||||||||||
##\s | A single whitespace character | |||||||||||||||
A single non-whitespace character | ||||||||||||||||
A tab character | ||||||||||||||||
Capturing brackets | Remember matching characters |
字符 | 替换文本 |
---|---|
2、…、$99 | 与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。 |
$& | 与 regexp 相匹配的子串。 |
$` | 位于匹配子串左侧的文本。 |
$’ | 位于匹配子串右侧的文本。 |
$$ | 允许替换中有一个字面值美元符号($) |
$n | 插入使用RegExp的第n次捕获圆括号的值 |
var myName = "Tao Yang";var nameRe = /^(\w+)\s(\w+)$/;var myNewName = myName.replace(nameRe, "$2 $1"); console.log(myNewName); //Yang Tao
使用正则表达式把尖括号(a8093152e673feb7aba1828c43532094)转换为命名的实体:67bffed8d39c986beaddeed3e8cd5568
var pieceOfHtml = "<p>This is a <span>paragraph</span></p>"; pieceOfHtml = pieceOfHtml.replace(/</g, "<"); pieceOfHtml = pieceOfHtml.replace(/>/g, ">"); console.log(pieceOfHtml); //<p>This is a <span>paragraph</span></p>
var dtstr = "2014-3-04T19:35:32Z"; dtstr = dtstr.replace(/\D/g, " "); console.log(dtstr); //2014 3 04 19 35 32var dtcomps = dtstr.split(" ");//在基于1的ISO 8610月份和基于0的日期格式之间转换dtcomps[1]--;var convdt = new Date(Date.UTC.apply(null, dtcomps)); console.log(convdt.toString()); //Wed Mar 05 2014 03:35:32 GMT+0800 (中国标准时间)
使用一个匿名函数作为setInterval()或setTimeout()方法调用的第一个参数
var intervalId = null; document.getElementById("redbox").addEventListener('click', startBox, false);function startBox() { if(intervalId == null) { var x = 100; intervalId = setInterval(function() { x += 5; var left = x + "px"; document.getElementById("redbox").style.left = left; }, 500); } else { clearInterval(intervalId); intervalId = null; } }
在第一个事件发生的时候,创建一个Date对象,当第二个时间发生的时候,创建一个新的Date对象,并且从第二个对象中减去第一个对象。两者之间的差以毫秒表示的,要转换为秒,就除以1000
两个日期可以相减,但是相加就成了拼接字符串
var firstDate = new Date(); setTimeout(function() { doEvent(firstDate); }, 25000);function doEvent() { var secondDate = new Date(); var diff = secondDate - firstDate; console.log(diff); //25001}
使用Number对象的 toString() 方法
var num = 255; console.log(num.toString(16)); //ff
遍历表中包含了数字值的列,将其转换为数字,并加和
querySelector() 方法返回文档中匹配指定 CSS 选择器的一个元素
如果你需要返回所有的元素,请使用 querySelectorAll() 方法替代
全局函数 parseInt() 和 parseFloat() 都把字符串转化为数字
var sum = 0;//使用querySelectorAll找到第二列的所有单元格var cells = document.querySelectorAll("td:nth-of-type(2)");for(var i=0, l=cells.length; i<l; i++) { sum += parseFloat(cells[i].firstChild.data); }
将角度转换为弧度
var radians = degrees * (Math.PI / 180);
将弧度转化为角度
var degrees = radians * (180 / Math.PI);
Math.min(x,y)方法可返回指定的数字中带有最低值的数字。
求出宽度和高度中较小的一个,用其除以2得到半径
var circleRadius = Math.min(elemengWidth, elemengHeight) / 2;
给指定页面元素的宽度、高度,通过将二者都除以2来找到其中心点
var x = elemengWidth / 2;var y = elemengHeight / 2;
Window.getComputedStyle()方法给出应用活动样式表后的元素的所有CSS属性的值,并解析这些值可能包含的任何基本计算。
getComputedStyle()
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>将一个SVG圆放入到一个p元素中</title> <style type="text/css"> #elem { width: 100%; height: 500px; border: 1px solid #ddd; background-color: #ddd; } </style></head><body> <p id="elem"> <svg width="100%" height="100%"> <circle id="circ" width="10" height="10" r="10" fill="#f90"> </svg> </p> <script type="text/javascript"> window.onload = window.onresize = function() { var box = document.getElementById("elem"); var style = window.getComputedStyle(box, null); var width = parseInt(style.getPropertyValue("width")); var height = parseInt(style.getPropertyValue("height")); console.log('w', width, 'h', height); var x = width / 2; var y = height / 2; var circleRadius = Math.min(width, height) / 2; var circ = document.getElementById("circ"); circ.setAttribute("r", circleRadius); circ.setAttribute("cx", x); circ.setAttribute("cy", y); console.log('r', circleRadius, ' cx', x, ' cy', y); } </script></body></html>
给定了一个圆的半径及圆弧角的角度值,求该圆弧的长度
使用Math.PI
把角度转换为弧度,并在公式中使用该结果来求得圆弧的长度
var radians = degrees * (Math.PI / 180);var arclength = radians * radians;
indexOf()、lastIndexOf()
var animals = new Array('dog', 'cat', 'seal', 'elephant', 'walrus', 'lion');var index = animals.indexOf('cat');var index2 = animals.lastIndexOf('lion'); console.log('i',index); //1console.log('i2',index2); //5
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
var nums = [2, 4, 199, 80, 400, 30, 90];var over = nums.findIndex(function(ele) { return (ele >= 100); }); console.log('nums',nums[over]); //199
concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。
arrayObject.concat(arrayX,arrayX,......,arrayX)
var fruitarray = []; fruitarray[0] = ['stranwberry', 'orange']; fruitarray[1] = ['lime', 'peach', 'banana']; fruitarray[2] = ['tangerine', 'apricot']; console.log('array',fruitarray.concat());var newArray = fruitarray.concat.apply([], fruitarray); console.log(newArray);
apply()与call()的区别
如何理解和熟练运用js中的call及apply?
obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);
call() & apply(),动态改变this
function add(a, b) { console.log('add', this); }function sum(a, b) { console.log('sum', this); } add(1, 2); //Windowsum(1, 2); //Windowadd.call(sum, 1, 2); //sum(a, b)sum.call(add, 1, 2); //add(a ,b)
arguments装换为数组, 返回的是数组,但是arguments本身保持不变
var arg = [].slice.call(arguments);// [].slice.call(document.getElementsByTagName('li'));
借用别人的方法
var foo = { name: 'jack', showName: function() { console.log('this name:',this.name); } }var bar = { name: 'rose'} foo.showName(); //jackfoo.showName.call(bar); //rose
实现继承
var Student = function(name, age, high) { Person.call(this, name, age); this.high = high; }
封装对象保证this的指向
var _this = this; _this.$box.on('mousedown', function()) { return _this.fndown.apply(_this); }
splice() 方法与 slice() 方法的作用是不同的,splice() 方法会直接对数组进行修改。
var animals = new Array('dog', 'cat', 'rabbit', 'pig', 'apple');// 从数组删除元素animals.splice(animals.indexOf('apple'), 1); console.log(animals); // ["dog", "cat", "rabbit", "pig"]// 替换animals.splice(animals.indexOf('pig'), 1, 'monkey'); console.log(animals); //["dog", "cat", "rabbit", "monkey"]// 使用循环和分割来替换和删除元素var charSets = ["ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab"];while(charSets.indexOf('ab') != -1) { charSets.splice(charSets.indexOf('ab'), 1, '**'); } console.log(charSets); //["**", "bb", "cd", "**", "cc", "**", "dd", "**"]while(charSets.indexOf('**') != -1) { charSets.splice(charSets.indexOf('**'), 1); } console.log(charSets); //["bb", "cd", "cc", "dd"]
不更改原数组,使用slice()
var animals = new Array('dog', 'cat', 'rabbit', 'pig', 'apple');var newAnimals = animals.slice(1, 2); console.log(animals); //["dog", "cat", "rabbit", "pig", "apple"]console.log(newAnimals); //["cat"]
Array.prototype.forEach()
var charSets = ["ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab"]; charSets.forEach(function(element, index, array) { if(element == 'ab') array[index] = '**'; }); console.log(charSets); //["**", "bb", "cd", "**", "cc", "**", "dd", "**"]
querySelectorAll()
可以将forEach()强制和一个NodeList一起使用
var cells = document.querySelectorAll('td + td'); [].forEach.call(cells, function(cell) { sum += parseFloat(cell.firstChild.data); });
将一个十进制的数组转化为新的等价的十六进制数组
map()方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
与forEach()不同,不会修改原数组,但是必须返回一个值
var decArray = [23, 3, 24, 45, 500, 9, 70];var hexArray = decArray.map(function(ele) { return ele.toString(16); }); console.log(decArray); //[23, 3, 24, 45, 500, 9, 70]console.log(hexArray); //["17", "3", "18", "2d", "1f4", "9", "46"]
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
var charSet = ['**', 'bb', 'cc', '**', 'cd'];var newArray = charSet.filter(function(element, index, array) { return element != "**"; }); console.log(newArray); //["bb", "cc", "cd"]
使用Array every()方法来检查每个元素是否符合给定的条件
some() 方法确保至少某些元素符合该条件
区别:every()方法只要函数返回一个false值,处理就会结束,而some()方法会继续测试每个元素,直至返回true,此时,不再验证其他元素,即可返回ture
function testValue(element, index, array) { var testExp = /^[a-zA-Z]+$/; return testExp.test(element); }var elemSet = ['**', 123, 'adv', '-', 45, 'AAA'];var result = elemSet.every(testValue);var result2 = elemSet.some(testValue); console.log(result); //falseconsole.log(result2); //truevar elemSet2 = ['aaa', 'animals', 'vvv']; result = elemSet2.every(testValue); result2 = elemSet2.some(testValue); console.log(result); //trueconsole.log(result2); //true
keys() 方法返回一个新的Array迭代器,它包含数组中每个索引的键。
var elemArray = {};var elem = document.forms[0].elements[0]; elemArray[elem.id] = elem.value;var elemArray = {name: 'yt', age:25};Object.keys(elemArray).forEach(function(key) { var value = elemArray[key]; console.log(value); });
声明式函数
匿名函数或函数构造函数
函数字面值或函数表达式
声明式函数,可以放置在代码中的任何位置;函数表达式,必须将其放置在使用函数的位置之前
// 在声明一个变量之前打印aconsole.log('a', a); //undefinedvar a;// 在声明一个变量并赋值console.log('aa', aa); //undefinedvar aa = 1;// 声明变量发生了提升,但是赋值并没有,赋值是在相应的位置发生的// 声明式函数,在访问该函数之前,提升将确保把函数声明移动到当前作用域的顶部console.log(mytest()); //successfunction mytest() { return 'success'; }// 使用函数表达式就会报错,变量可能声明了,但没有实例化,但是你的代码试图将这个变量当做一个函数对待console.log(mytest2()); //TypeError: mytest2 is not a functionvar mytest2 = function() { return 'success2'; }
function otherFunction(x, y, z) { x(y, z); }// 可以像传递一个命名的变量一样,将一个函数作为参数传递给另一个函数var param = function func(a1, a2) { alert(a1 + " " + a2); }; otherFunction(param, "Hello", "World");
函数式编程和JavaScript
高阶函数: 一个函数接受另一个函数作为参数,或者返回一个函数,或者两者都具备
函数式编程: 对应用程序复杂性进行抽象的一种方式,使用整齐、干净的函数调用替代了复杂的循环和条件语句(代码可读性高)
比如:将数组中的所有数字相加
// for循环相加var nums = [1, 34, 3, 15, 4, 18];var sum = 0;for(var i = 0; i < nums.length; i++) { sum += nums[i]; } console.log('sum', sum); //75var nums2 = [1, 34, 3, 15, 4, 18];var sum2 = nums2.reduce(function(n1, n2) { return n1 + n2; }); console.log('sum2', sum2); //75
arr.reduce([callback, initialValue]) 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。
想要实现一个函数,它递归地遍历一个数组并返回一个反向的数组字符串
缺点:递归很消耗内存
// 阶乘function factorial(n) { return n == 1 ? n : n * factorial(n - 1); } console.log('阶乘', factorial(4)); // 24// 斐波那契var fibonacci = function(n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); } console.log('斐波那契', fibonacci(10)); //55// 使用一个递归函数字面值来反转数组元素,从最大长度开始,每次迭代都将这个值自减// 当为 0 时,返回字符串var reverseArrary = function(x, index, str) { return index == 0 ? str : reverseArrary(x, --index, (str += " " + x[index])); }var arr = ['apple', 'orange', 'peach', 'lime'];var str = reverseArrary(arr, arr.length, ""); console.log('str', str); //lime peach orange apple// 如果要反过来,按照顺序把数组连接为一个字符串var orderArray = function(x, i, str) { return i == x.length - 1 ? str : orderArray(x, ++i, (str += x[i] + " ")); }var numArr = [1, 2, 3, 4];var numStr = orderArray(numArr, -1, ""); console.log('numStr', numStr); //1 2 3 4
在程序的输出中,3个外围的 console.log()
立即被处理了
队列中下一个事件是第一个 noBlock()
函数调用,其中又调用了 factorial()
,记录了其运行时候的活动,最后跟着回调函数的调用
第二次同样地调用了 callBack()
第三次调用 callBack()
的时候,回调函数中的调用针对第一次 callBack()
,并使用了第一次函数调用的最终结果:6
<script type="text/javascript">function factorial(n) { console.log('n', n); return n == 1 ? 1 : n * factorial(n - 1); }function noBlock(n, callback) { setTimeout(function() { var val = factorial(n); if(callback && typeof callback == 'function') { callback(val); } }, 0); } console.log('Top of the morning to you'); noBlock(3, function(n) { console.log('first call ends width ' + n); noBlock(n, function(m) { console.log('final result is ' + m); }); });var tst = 0;for(var i = 0; i < 10; i++) { tst += i; } console.log('value of tst is ' + tst); noBlock(4, function(n) { console.log('end result is ' + n); }); console.log('not doing too much');</script>
相关推荐:
The above is the detailed content of The first chapters 1~3 of "JavaScript Classic Examples" (Collection). For more information, please follow other related articles on the PHP Chinese website!