Home  >  Article  >  Web Front-end  >  The first chapters 1~3 of "JavaScript Classic Examples" (Collection)

The first chapters 1~3 of "JavaScript Classic Examples" (Collection)

php是最好的语言
php是最好的语言Original
2018-08-07 09:42:511397browse

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.

Chapter 1 JavaScript is more than just simple building blocks

1.1 The difference between JavaScript objects, primitive types, and literals

  • 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

1.2 Extracting a list from a string

  • 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 you want to verify that a variable has been defined and is a string, And it is not empty

  • if(typeof unknowVariable === 'string' && unknowVariable.length > 0) {...}
1.4 Inserting special characters

  • Want to insert a special character into the string, such as a newline

  • Escape sequences all start with a

    backslash (\)

1.5 Use new string replacement pattern

  • Use the replace method of the String object and a

    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.

Regular expression special characters

CharactersMatch Example^ Matches the beginning of the input /^This/ Matches This is…##*?{n}##{n,}matches n or more times/ap{2,}/ matches apple p, but does not match p in apie Characters/a.e/ in apppppple matches ape and axeAny characters in square brackets/a[px]e/ matches ape axe but not apxe[^…]Any character except square brackets/a[^px]/ matches ale but not ape ax\bmatches word boundaries /\bno/ matches the first no in nono\Bmatches a non-word boundary/\Bno / Matches the second no\dnumber in nono from 0 to 9/\d{3}/ Matches Now in 123 The 123\D matches any non-numeric character /\D{2,4}/ matches the Now in# in Now in 123 /\w/ matches j##\W Matches any non-word characters (non-letters, arrays and underscores) /\W/ matches %## in 100% ##\SA single non-whitespace character\tA tab character##(x)
var searchString = "Now is the time, this is the tame";var re = /t\w{2}e/g;var replacement = searchString.replace(re, 'place');
console.log(replacement);  //Now is the place, this is the place

1.6 找到并突出显示一个模式的所有实例

  • RegExp exec() 方法用于检索字符串中的正则表达式的匹配

  • RegExpObject.exec(string)

  • 返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null

var searchString2 = "Now is the time and this is the time and that is the time";var parttern = /t\w*e/g;  //\w 匹配任何单词字符var matchArray;var str = "";//用regexp exec检查模式,如果不为空,处理它while((matchArray = parttern.exec(searchString2)) != null) {
    str += "at " + matchArray.index + " we found " + matchArray[0] + "\n";
}
console.log(str);// at 7 we found the// at 11 we found time// at 28 we found the// at 32 we found time// at 49 we found the// at 53 we found time
//实例1-1document.getElementById("searchSubmit").onclick = function() {

    //获取模式
    var pattern = document.getElementById("pattern").value;    var re = new RegExp(pattern, "g");    //获取字符串
    var searchString = document.getElementById("inComing").value;    var matchArray;    var resultString = "<pre class="brush:php;toolbar:false">";    var first = 0;    var last = 0;    //找到每一个匹配
    while((matchArray = re.exec(searchString)) != null) {
        last = matchArray.index;        //获取所有匹配的字符串,将其连接起来
        resultString += searchString.substring(first, last);        //使用class,添加匹配的字符串
        resultString += &#39;<span class="found">&#39; + matchArray[0] + &#39;</span>&#39;;
        first = re.lastIndex;
    }    //完成字符串
    resultString += searchString.substring(first, searchString.length);
    resultString += "
"; //插入页面 document.getElementById("searchResult").innerHTML = resultString; }

1.7 使用捕获圆括号交换一个字符串中的单词

  • 交换名称,让姓氏先出现

  • 解决:使用捕获圆括号和一个正则表达式在字符串中找到并记住他们的名字,然后互换他们

  • replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

/ 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,m}
/ap{2,4}/ matches 4 p
[…]
##\w Matches any word characters (letters, arrays and underscores
# in javaScript
#\n Matches a newline
##\s A single whitespace 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

1.8 使用命名实体来替代HTML标签

  • 使用正则表达式把尖括号(a8093152e673feb7aba1828c43532094)转换为命名的实体:67bffed8d39c986beaddeed3e8cd5568

var pieceOfHtml = "<p>This is a <span>paragraph</span></p>";
pieceOfHtml = pieceOfHtml.replace(/</g, "&lt;");
pieceOfHtml = pieceOfHtml.replace(/>/g, "&gt;");
console.log(pieceOfHtml); //&lt;p&gt;This is a &lt;span&gt;paragraph&lt;/span&gt;&lt;/p&gt;

1.9 ISO 8610格式的日期转换为Date对象可接受的一种形式

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 (中国标准时间)

1.10 使用带有定时器的函数闭包

  • 使用一个匿名函数作为setInterval()或setTimeout()方法调用的第一个参数

var intervalId = null;
document.getElementById("redbox").addEventListener(&#39;click&#39;, 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;
    }
}

1.11 记录两个事件之间消耗的时间

  • 在第一个事件发生的时候,创建一个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}

1.12 十进制数转化为十六进制值

  • 使用Number对象的 toString() 方法

var num = 255;
console.log(num.toString(16));  //ff

1.13 想要将表中一列的所有数字加和

  • 遍历表中包含了数字值的列,将其转换为数字,并加和

  • 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);
}

1.14 在角度和弧度之间转换

  • 将角度转换为弧度

var radians = degrees * (Math.PI / 180);
  • 将弧度转化为角度

var degrees = radians * (180 / Math.PI);

1.15 找到页面元素可容纳的一个圆的半径和圆心

  • 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(&#39;w&#39;, width, &#39;h&#39;, 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(&#39;r&#39;, circleRadius, &#39; cx&#39;, x, &#39; cy&#39;, y);
    }    </script></body></html>

1.16 计算圆弧的长度

  • 给定了一个圆的半径及圆弧角的角度值,求该圆弧的长度

  • 使用Math.PI把角度转换为弧度,并在公式中使用该结果来求得圆弧的长度

var radians = degrees * (Math.PI / 180);var arclength = radians * radians;

第2章 JavaScript数组

2.1 在数组中搜索

  • indexOf()、lastIndexOf()

var animals = new Array(&#39;dog&#39;, &#39;cat&#39;, &#39;seal&#39;, &#39;elephant&#39;, &#39;walrus&#39;, &#39;lion&#39;);var index = animals.indexOf(&#39;cat&#39;);var index2 = animals.lastIndexOf(&#39;lion&#39;);
console.log(&#39;i&#39;,index);  //1console.log(&#39;i2&#39;,index2);  //5
  • findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

var nums = [2, 4, 199, 80, 400, 30, 90];var over = nums.findIndex(function(ele) {
    return (ele >= 100);
});
console.log(&#39;nums&#39;,nums[over]);  //199

2.2 用concat()和apply()将一个二维数组扁平化

  • concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。

    • arrayObject.concat(arrayX,arrayX,......,arrayX)

var fruitarray = [];
fruitarray[0] = [&#39;stranwberry&#39;, &#39;orange&#39;];
fruitarray[1] = [&#39;lime&#39;, &#39;peach&#39;, &#39;banana&#39;];
fruitarray[2] = [&#39;tangerine&#39;, &#39;apricot&#39;];
console.log(&#39;array&#39;,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(&#39;add&#39;, this);
}function sum(a, b) {
    console.log(&#39;sum&#39;, 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(&#39;li&#39;));
  • 借用别人的方法

var foo = {
    name: &#39;jack&#39;,
    showName: function() {
        console.log(&#39;this name:&#39;,this.name);
    }
}var bar = {
    name: &#39;rose&#39;}
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(&#39;mousedown&#39;, function()) {
    return _this.fndown.apply(_this);
}

2.3 删除或替换数组元素

  • splice() 方法与 slice() 方法的作用是不同的,splice() 方法会直接对数组进行修改。

var animals = new Array(&#39;dog&#39;, &#39;cat&#39;, &#39;rabbit&#39;, &#39;pig&#39;, &#39;apple&#39;);// 从数组删除元素animals.splice(animals.indexOf(&#39;apple&#39;), 1);
console.log(animals);  // ["dog", "cat", "rabbit", "pig"]// 替换animals.splice(animals.indexOf(&#39;pig&#39;), 1, &#39;monkey&#39;);
console.log(animals);  //["dog", "cat", "rabbit", "monkey"]// 使用循环和分割来替换和删除元素var charSets = ["ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab"];while(charSets.indexOf(&#39;ab&#39;) != -1) {
    charSets.splice(charSets.indexOf(&#39;ab&#39;), 1, &#39;**&#39;);
}
console.log(charSets);  //["**", "bb", "cd", "**", "cc", "**", "dd", "**"]while(charSets.indexOf(&#39;**&#39;) != -1) {
    charSets.splice(charSets.indexOf(&#39;**&#39;), 1);
}
console.log(charSets); //["bb", "cd", "cc", "dd"]

2.4 提取一个数组中的一部分

  • 不更改原数组,使用slice()

var animals = new Array(&#39;dog&#39;, &#39;cat&#39;, &#39;rabbit&#39;, &#39;pig&#39;, &#39;apple&#39;);var newAnimals = animals.slice(1, 2);
console.log(animals);  //["dog", "cat", "rabbit", "pig", "apple"]console.log(newAnimals);  //["cat"]

2.5 对每一个数组元素应用一个函数

  • Array.prototype.forEach()

var charSets = ["ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab"];
charSets.forEach(function(element, index, array) {
    if(element == &#39;ab&#39;) array[index] = &#39;**&#39;;
});
console.log(charSets);  //["**", "bb", "cd", "**", "cc", "**", "dd", "**"]

2.6 使用forEach()和call()遍历querySelectorAll()的结果

  • querySelectorAll()

  • 可以将forEach()强制和一个NodeList一起使用

var cells = document.querySelectorAll(&#39;td + td&#39;);
[].forEach.call(cells, function(cell) {
    sum += parseFloat(cell.firstChild.data);
});

2.7 对数组中的每个元素执行一个函数并返回一个新数组

  • 将一个十进制的数组转化为新的等价的十六进制数组

  • 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"]

2.8 创建一个过滤后的数组

  • filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

var charSet = [&#39;**&#39;, &#39;bb&#39;, &#39;cc&#39;, &#39;**&#39;, &#39;cd&#39;];var newArray = charSet.filter(function(element, index, array) {
    return element != "**";
});
console.log(newArray);  //["bb", "cc", "cd"]

2.9 验证数组内容

  • 使用Array every()方法来检查每个元素是否符合给定的条件

  • some() 方法确保至少某些元素符合该条件

  • 区别:every()方法只要函数返回一个false值,处理就会结束,而some()方法会继续测试每个元素,直至返回true,此时,不再验证其他元素,即可返回ture

function testValue(element, index, array) {
    var testExp = /^[a-zA-Z]+$/;    return testExp.test(element);
}var elemSet = [&#39;**&#39;, 123, &#39;adv&#39;, &#39;-&#39;, 45, &#39;AAA&#39;];var result = elemSet.every(testValue);var result2 = elemSet.some(testValue);
console.log(result);  //falseconsole.log(result2);  //truevar elemSet2 = [&#39;aaa&#39;, &#39;animals&#39;, &#39;vvv&#39;];
result = elemSet2.every(testValue);
result2 = elemSet2.some(testValue);
console.log(result);  //trueconsole.log(result2);  //true

2.10 使用一个关联数组来存储表单元素名和值

  • keys() 方法返回一个新的Array迭代器,它包含数组中每个索引的键。

var elemArray = {};var elem = document.forms[0].elements[0];
elemArray[elem.id] = elem.value;var elemArray = {name: &#39;yt&#39;, age:25};Object.keys(elemArray).forEach(function(key) {
    var value = elemArray[key];
    console.log(value);
});

第3章 JavaScript的构建块

3种基本的创建函数方式:

  • 声明式函数

  • 匿名函数或函数构造函数

  • 函数字面值或函数表达式

3.1 放置函数并提升

  • 声明式函数,可以放置在代码中的任何位置;函数表达式,必须将其放置在使用函数的位置之前

// 在声明一个变量之前打印aconsole.log(&#39;a&#39;, a);  //undefinedvar a;// 在声明一个变量并赋值console.log(&#39;aa&#39;, aa);  //undefinedvar aa = 1;// 声明变量发生了提升,但是赋值并没有,赋值是在相应的位置发生的// 声明式函数,在访问该函数之前,提升将确保把函数声明移动到当前作用域的顶部console.log(mytest());  //successfunction mytest() {
    return &#39;success&#39;;
}// 使用函数表达式就会报错,变量可能声明了,但没有实例化,但是你的代码试图将这个变量当做一个函数对待console.log(mytest2());  //TypeError: mytest2 is not a functionvar mytest2 = function() {
    return &#39;success2&#39;;
}

3.2 把一个函数当做参数传递给另一个函数

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(&#39;sum&#39;, sum);  //75var nums2 = [1, 34, 3, 15, 4, 18];var sum2 = nums2.reduce(function(n1, n2) {
    return n1 + n2;
});
console.log(&#39;sum2&#39;, sum2);  //75
  • arr.reduce([callback, initialValue]) 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

3.3 实现递归算法

  • 想要实现一个函数,它递归地遍历一个数组并返回一个反向的数组字符串

  • 缺点:递归很消耗内存

// 阶乘function factorial(n) {
    return n == 1 ? n : n * factorial(n - 1);
}
console.log(&#39;阶乘&#39;, factorial(4));  // 24// 斐波那契var fibonacci = function(n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(&#39;斐波那契&#39;, fibonacci(10));  //55// 使用一个递归函数字面值来反转数组元素,从最大长度开始,每次迭代都将这个值自减// 当为 0 时,返回字符串var reverseArrary = function(x, index, str) {
    return index == 0 ? str : reverseArrary(x, --index, (str += " " + x[index]));
}var arr = [&#39;apple&#39;, &#39;orange&#39;, &#39;peach&#39;, &#39;lime&#39;];var str = reverseArrary(arr, arr.length, "");
console.log(&#39;str&#39;, 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(&#39;numStr&#39;, numStr);  //1 2 3 4

3.4 使用一个定时器和回调防止代码阻塞

  • 在程序的输出中,3个外围的 console.log() 立即被处理了

  • 队列中下一个事件是第一个 noBlock() 函数调用,其中又调用了 factorial() ,记录了其运行时候的活动,最后跟着回调函数的调用

  • 第二次同样地调用了 callBack()

  • 第三次调用 callBack() 的时候,回调函数中的调用针对第一次 callBack() ,并使用了第一次函数调用的最终结果:6

<script type="text/javascript">function factorial(n) {
    console.log(&#39;n&#39;, n);    return n == 1 ? 1 : n * factorial(n - 1);
}function noBlock(n, callback) {
    setTimeout(function() {
        var val = factorial(n);        if(callback && typeof callback == &#39;function&#39;) {
            callback(val);
        }
    }, 0);
}
console.log(&#39;Top of the morning to you&#39;);
noBlock(3, function(n) {
    console.log(&#39;first call ends width &#39; + n);
    noBlock(n, function(m) {
        console.log(&#39;final result is &#39; + m);
    });
});var tst = 0;for(var i = 0; i < 10; i++) {
    tst += i;
}
console.log(&#39;value of tst is &#39; + tst);
noBlock(4, function(n) {
    console.log(&#39;end result is &#39; + n);
});
console.log(&#39;not doing too much&#39;);</script>

相关推荐:

收藏Javascript中常用的55个经典技巧

JavaScript 经典实例日常收集整理(常用经典)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn