Maison > interface Web > js tutoriel > le corps du texte

Les premiers chapitres 1 à 3 de 'JavaScript Classic Exemples' (Collection)

php是最好的语言
Libérer: 2018-08-07 09:42:51
original
1363 Les gens l'ont consulté

Chaque section des « Exemples JavaScript classiques » contient des exemples de code détaillés, résolvant les problèmes que nous rencontrons souvent et donnant des techniques pour créer des applications Web dans n'importe quel navigateur. Si ces codes vous sont utiles, collez-les simplement. Vous pouvez terminer le travail rapidement et en apprendre beaucoup sur JavaScript.

Chapitre 1 JavaScript est plus que de simples blocs de construction

1.1 La différence entre les objets JavaScript, les types primitifs et les littéraux

  • 5 types de base : string, valeur numérique, valeur booléenne, null, non défini. Il existe 3 objets constructeur correspondants : string, Number, Boolean

  • Les variables de type de base sont strictement égales aux valeurs littérales des mots, tandis que l'objet. les instances ne le font pas, car les types primitifs sont comparés par valeur et les valeurs sont des littéraux

var num1 = 123;var num2 = new Number(123);
console.log(typeof num1);  //number console.log(typeof num2);  //object
Copier après la connexion

1.2 Extraire une liste d'une chaîne

  • Avant l'extraction : This is a list of items: cherries, limes, oranges, apples.

  • Après l'extraction : ['cherries','limes','oranges','apples']

  • indexOf() La méthode renvoie la première occurrence d'une valeur de chaîne spécifiée dans une chaîne. La méthode

  • substring() est utilisée pour extraire les caractères entre deux indices spécifiés dans la chaîne. La méthode

  • split() est utilisée pour diviser une chaîne en un tableau de chaînes.

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"]
Copier après la connexion

1.3 Vérification d'une chaîne existante et non vide

  • Vous souhaitez vérifier qu'une variable a été définie et est un caractère chaîne, et elle n'est pas vide

if(typeof unknowVariable === 'string' && unknowVariable.length > 0) {...}
Copier après la connexion

1.4 Insérer des caractères spéciaux

  • Vous souhaitez insérer un caractère spécial dans la chaîne, par exemple Une nouvelle ligne

  • séquence d'échappement commence par une contre-oblique()

1.5 Remplacer par une nouvelle chaîne Le motif

  • utilise la méthode replace de l'objet String et une méthode expression régulière

  • replace() est utilisé pour remplacer certains caractères par d'autres caractères dans une chaîne, ou remplacer une sous-chaîne qui correspond à une expression régulière.

Caractères spéciaux d'expression régulière

字符匹配例子
^匹配输入的开头/^This/ 匹配This is…
/ 匹配This is the end

*匹配0次或多次/se*/ 匹配s seeee或se
?匹配0次或1次/ap?/ 匹配apple and and
+匹配1次或多次/ap+/ 匹配apple 但是不匹配and
{n}严格匹配n次/ap{2}/ 严格匹配apple 但是不匹配apie
{n,}匹配n次或多次/ap{2,}/ 匹配apple中的p,但是不匹配apie中的p
{n,m}至少匹配n次,之多匹配m
除换行以外的任何字符
/ap{2,4}/ 匹配apppppple中的4个p
/a.e/ 匹配ape和axe
[…]方括号中的任何字符/a[px]e/ 匹配ape axe 但是不匹配apxe
[^…]除了方括号以外的任何字符/a[^px]/ 匹配ale 但是不匹配ape axe
b匹配单词边界/bno/ 匹配nono中的第一个no
B匹配非单词边界/Bno/ 匹配nono中的第二个no
d数字0到9/d{3}/ 匹配Now in 123 中的123
D匹配任何非数字字符/D{2,4}/ 匹配Now in 123 中的Now in
w匹配任何单词字符(字母、数组和下划线/w/ 匹配javaScript中的j
W匹配任何非单词字符(非字母、数组和下划线)/W/ 匹配100%中的%
n匹配一个换行
s一个单个的空白字符
S一个单个的非空白字符
t一个制表符
(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
Copier après la connexion

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
Copier après la connexion
//实例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; }
Copier après la connexion

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

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

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

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

字符替换文本
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
Copier après la connexion

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

  • 使用正则表达式把尖括号(<>)转换为命名的实体:<和>

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;
Copier après la connexion

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 (中国标准时间)
Copier après la connexion

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;
    }
}
Copier après la connexion

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}
Copier après la connexion

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

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

var num = 255;
console.log(num.toString(16));  //ff
Copier après la connexion

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);
}
Copier après la connexion

1.14 在角度和弧度之间转换

  • 将角度转换为弧度

var radians = degrees * (Math.PI / 180);
Copier après la connexion
  • 将弧度转化为角度

var degrees = radians * (180 / Math.PI);
Copier après la connexion

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

  • Math.min(x,y)方法可返回指定的数字中带有最低值的数字。

  • 求出宽度和高度中较小的一个,用其除以2得到半径

var circleRadius = Math.min(elemengWidth, elemengHeight) / 2;
Copier après la connexion
  • 给指定页面元素的宽度、高度,通过将二者都除以2来找到其中心点

var x = elemengWidth / 2;var y = elemengHeight / 2;
Copier après la connexion
  • 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>
Copier après la connexion

1.16 计算圆弧的长度

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

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

var radians = degrees * (Math.PI / 180);var arclength = radians * radians;
Copier après la connexion

第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
Copier après la connexion
  • 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
Copier après la connexion

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);
Copier après la connexion
  • 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)
Copier après la connexion
  • arguments装换为数组, 返回的是数组,但是arguments本身保持不变

var arg = [].slice.call(arguments);// [].slice.call(document.getElementsByTagName(&#39;li&#39;));
Copier après la connexion
  • 借用别人的方法

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
Copier après la connexion
  • 实现继承

var Student = function(name, age, high) {
    Person.call(this, name, age);    this.high = high;
}
Copier après la connexion
  • 封装对象保证this的指向

var _this = this;
_this.$box.on(&#39;mousedown&#39;, function()) {
    return _this.fndown.apply(_this);
}
Copier après la connexion

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"]
Copier après la connexion

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"]
Copier après la connexion

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", "**"]
Copier après la connexion

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);
});
Copier après la connexion

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"]
Copier après la connexion

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"]
Copier après la connexion

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
Copier après la connexion

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);
});
Copier après la connexion

第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;;
}
Copier après la connexion

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

function otherFunction(x, y, z) {
    x(y, z);
}// 可以像传递一个命名的变量一样,将一个函数作为参数传递给另一个函数var param = function func(a1, a2) { alert(a1 + " " + a2); };
otherFunction(param, "Hello", "World");
Copier après la connexion
  • 函数式编程和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
Copier après la connexion
  • 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
Copier après la connexion

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>
Copier après la connexion

相关推荐:

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

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!