🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#JavaScript概述 - <a href="#no1">1.1 JavaScript语言核心</a> - <a href="#no2">1.2 客户端JavaScript参考</a> ##<a name="no1">1.1 JavaScript语言核心</a> > `JavaScript`中两个非常重要的数据类型是对象和数组。 # > 通过方括号定义数组元素和通过花括号定义对象属性名和属性值之间的映射关系的语法称为初始化表达式。 # > 函数是带有名称和参数的`JavaScript`代码段,可以一次定义多次调用。 # > 当函数赋值给对象的属性,我们称为“方法”,所有的`JavaScript`对象都含有方法。 # ###求绝对值的函数 function abs(num){ if(num > 0){ return x; }else{ return -x; } } ###计算阶乘的函数 function factorial(n){ var product = 1; while(n > 1){ product *= n; n--; } return product; } factorial(5); //=> 5 * 4 * 3 * 2 * 1 = 120 **实现循环的另一种写法** function factorial2(n){ var i, product = 1; for(i = 2;i < n; i++){ product *= i; } return product; } factorial(5); //=> 1 * 2 * 3 * 4 * 5= 120 ###面向对象编程demo function Ponit(x, y){ this.x = x; this.y = y; } var p = new Ponit(1,1); Ponit.prototype.r = function(){ return Math.sqrt(this.x * this.x + this.y * this.y); }; console.log(p.r()); //=> 1.4142135623730951 ##<a name="no2">1.2 客户端JavaScript参考</a> > `JavaScript`代码可以通过`<script>`标签来嵌入到`HTML`文件中。 ###通过脚本来操纵`HTML`文档内容 // 在document中的一个指定区域输出调试信息 // 如果document不存在这样一个区域,则创建一个 function debug(msg){ var log = document.getElementById('debuglog'); if(!log){ log = document.createElement('div'); log.id = 'debuglog'; log.innerHTML = '<h1>Debug Log</h1>'; document.body.appendChild(log); } var pre = document.createElement('pre'); var text = document.createTextNode(msg); pre.appendChild(text); log.appendChild(pre); } debug('测试文本'); > `load`事件只有在文档加载完成之后才会触发,通常需要等待`load`事件发生后才开始执行`JavaScript`代码。