<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>函数,对象</title>
</head>
<body>
<script type="text/javascript">
'use strict'
//定义函数,两种方法
//方法一
function methods(x) {
if (x < 0) {
return -x;
} else {
return x;
}
}
//方法二
var xx = function (x) {
if (x < 0) {
return -x;
} else {
return x;
}
}
//调用,传入的参数可多可少
methods(2, 4, -6);//2
methods();//undefined
xx(-2, 'r');//2
xx();//undefined
//防止undefined
var xxx = function (x) {
//类型比较,抛出异常
if(typeof x !== 'number'){
throw 'this is not a number';
}
if (x < 0) {
return -x;
} else {
return x;
}
}
xxx('a',12);//day03.html?_ijt=4heq2cefvmlfk3dcusn8rcuqga:37 Uncaught this is not a number
//arguments只在函数内部起作用,指向当前函数调用者传入的所有参数,
// 作用,可以拿到传入的所有参数,也就是说,即使不定义任何参数,也能获取传入参数的值
function aa(){
if (arguments.length === 0){
return 0;
}
var y = arguments[0];
return y>10?11:9;
}
aa(1);//9
aa(33);//11
//rest参数(es6引入)
function bb(a, b, ...rest){
console.log(a+':'+b);//1:2
console.log(rest);//[3, 4]
}
bb(1,2,3,4)
//变量作用域,var申明的变量是有作用域的
//(1)函数体外不能引用函数体内的函数,因为使用了'use strict'严格控制模式
function qq(){
var j=9;
j+=1;
console.log(j);//j=10
}
j+=2;//Uncaught ReferenceError: qq is not defined
//(2)函数可以嵌套,即函数里可以有函数,变量相同时,按照就近原则赋值
function ww(){
var y = 2;
function pp() {
var y='S';
console.log(y);//y值为s
}
console.log(y);//y值为2
pp();
}
//变量提升,即可以先使用,后定义,并不会报错,提升的是指未定义之前就用,
//但是后面只能起申明,不能赋值
function mm() {
var x = 'w'+z;
var y =12+z
console.log(x);//x为wundefined
console.log(y);//y为NaN
var z = 3;
}
//全局作用域
//不在函数体内定义的变量具有全局作用域,window是JavaScript默认的全局对象,
// 实际上全局作用域的变量被绑到window的一个属性
var d ='hello';
alert(d);//hello
alert(window.d);//hello
//所以d与window。d作用是一致的,window是可省略的
/*刚开始就说了,函数有两种定义方式,其实以变量方式 var x = function(){}定义的函数
是一个全局变量
* */
//局部作用域:一般指变量的作用域是在函数内部,外部是无法使用的,但是,注意
//for循环是无法定义局部变量的,即即使for中变量,也可以在当前函数体中使用
function pp() {
for (var i = 0; i <5 ; i++) {
}
i+=1;//不会报错,仍然可以使用变量i;
console.log(i);//i值为6
}
/*但是上面显然很作用域很模糊,所有es6引入了新的关键字let,这个关键字可以是for中的变量
的作用域只在for循环里面,出了for循环,就报错
*/
function kk(){
for (let i = 0; i <5 ; i++) {
}
i+=1;//报错,ReferenceError: i is not defined
console.log(i);
}
//常量
/*
es6,之前,想要声明一个变量是不可以的,通常把变量名大写来表示是一个变量,
但是还是可以随便改变的,es6引入了新的关键字const定义常量
*/
const PI = 3.14;
// PI = 4;//编译就报错
//方法:在一个对象中绑定函数,称为这个对象的方法
var per = {
name:'大大',
age: function () {
return 18;
}
};
console.log(per.name);//大大
per.age();//18
//标准对象
typeof 123; // 'number'
typeof NaN; // 'number'
typeof 'str'; // 'string'
typeof Math.abs; // 'function'
typeof null; // 'object'
typeof []; // 'object'
typeof {}; // 'object'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
//Date
var now = new Date();
now; //
now.getFullYear(); // 2019, 年份
now.getMonth(); // 0, 月份,注意月份范围是0~11,0表示一月
now.getDate(); // 17, 表示17号
now.getDay(); // 5, 表示星期五
now.getHours(); // 24小时制
now.getMinutes(); // 分钟
now.getSeconds(); // 秒
now.getMilliseconds(); //毫秒数
now.getTime(); // 以number形式表示的时间戳
</script>
</body>
</html>
es6-day03-函数标准对象
猜你喜欢
转载自blog.csdn.net/linyiwwy/article/details/104020424
今日推荐
周排行