js基础

2018-08-17  本文已影响0人  pubalabala

JavaScript基础

<!--
    1.js是javaScript的缩写,是一门脚本语言。专门用来负责网页上的行为(可以直接写到网页中)。
    
    2.在哪儿写js代码
    a.可以写在script标签中(理论上script标签可以放到html文件中的任何位置,实际开发的时候一般放在head或者body中)
    b.写到标签的事件属性中(例如:onclick)
    c.写到外部的js文件中(.js)
    
    3.js在网页中能做什么事情
    a.在网页的不同的位置插入html代码
    b.修改某个标签的内容
    c.修改标签的样式
    
    4.怎么写
-->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        
        <!--导入外部的js文件-->
        <!--<script src="js/index.js"></script>-->
        <script src='js/07-数据类型.js'>
            
        </script>
        
        <!--一个html中可以在多个位置插入script标签-->
        <script type="text/javascript">
            // 在这儿写js代码
            function insertP(){
                document.write('<p>python</p>')
            }
        </script>
        
    </head>
    <body>
        
        <h1 id="hh">千锋的所有学科</h1>
        
        <button onclick="window.alert('按钮被点击')"></button>
        
        <!--修改标签的样式-->
        <button onclick="document.getElementById('hh').style.color = 'red'">修改样式</button>
        
        <!--修改标签内容-->
        <button onclick="document.getElementById('hh').innerHTML='千锋的所有老师'">修改内容</button>
        
        <!--往html中插入内容-->
        <script type="text/javascript">
            for (var i = 0; i <100; i++) {
                document.write("<p>按施工队</p>")
            }
        </script>
        
        
    </body>
    
    
</html>

JavaScript基础语法

//1. js中的注释
//这是单行注释
/*
 这个是多行注释
 */

//2.语句
//一条语句结束需要加分号(现在的js版本也可以不用写)
//一行写多条语句必须使用分号隔开


//3.js没有缩进问题,用{}表示一个块

//4.基本数据类型
//Number(数字)、String(字符串)、Boolean(布尔)、Array(数组)-- 列表、Object(对象)--字典、Function(函数)、null、undefined


//在控制台中打印括号中的内容,功能和python中的print
        
console.log('hello world');
console.log('你好,python');


//5.字面量
//数字字面量
89;
100;
10.34;
3e8;

//字符串字面量
'abc';
"abc";

//布尔字面量
true;
false;

//数组字面量
[1,2,'ban',true];
[];

//对象的字面量(对象的key值又是属性,不用加引号)
var dict = {a:'abc', b:'hh'};
//console.log(dict.a, dict['b']);

//6.标识符
//使用标识符来命名
//a.由字母、数字、_和$组成,数字不能开头
var s8uu_$;

//b.不能关键字
//var for

//c.大小写敏感,y和Y不一样
//d.规范:见名知意

变量的声明

//在js中可以通过声明变量来保存数据
/*
 * 1.语法
 * var 变量名;
 * var 变量名 = 初值;
 * 说明: var是关键字;
 *       变量名:标识符,不能随意使用_或者$开头;驼峰式命名规则(第一个单词首字母小写,后面每个单词的首字母大写)
 */
//声明变量
var userName;
//给变量赋值
userName = 'Wang';
console.log(userName)

var score = 100
console.log(score)


//同时声明多个变量
var name, age, sex;
var name1='abc', age1 = 18, sex;  

//一个变量可以存储任意类型的值;声明变量的时候,变量没有赋值,默认是undefined
var a = 'abc'
a = 100

a = score

运算符

//1.数学运算符:+, -, *, /, %, ++, --
//a._,-,*, %和数学中的求和、求差以及求乘积,取余是一样的
var a = 10+20;
var b = 20 - 10;
var c = 10*20;
var d = 7 % 2

//b./ 和数学中的除一样
var e = 5/2
console.log(e)

//c.++,--(单目运算符)
/*
 * 语法: 变量++/变量-- ; ++变量/--变量
 * ++: 自加一
 * --:自减一
 */
var a1 = 10
var b1 = 10
a1++
++b1
console.log(a1,b1) // 11, 11

a1--
--b1
console.log(a1, b1) // 10, 10

var c1 = a1++    // ++/--写到后面的时候,先赋值,再自加/自减
var c2 = ++b1    // ++/--写到前面的时候,先自加/自减,再赋值
console.log(c1, c2)   

//2.比较运算符: >,<,==(相等),!=, >=,<=, ===(完全相等), !==,>==, <==
//结果都是布尔值
console.log(10 > 20)  // false
console.log(10<20) 

//==:判断值是否相等
console.log(5==5)   //true
console.log(5=='5')  //true

//===:判断值和类型是否相等
console.log(5===5)  //true
console.log(5==='5')  //false

console.log(5!=5, '5'!=5)  //false,false
console.log(5!==5, '5'!==5) //false,true

//3.逻辑运算符:&&(与), ||(或), !(非)
console.log('与:',true && true, true && false)
console.log('或',true || false, false || false) 
console.log('非',!true, !false)  

//4.赋值运算符: =, +=, -= , *=, /=, %=
//赋值运算符的左边必须是变量
//和python的语法一样
var a = 100;
a += 10  // a = a+10
a -= 10
a *= 10
a /= 10
a %= 10
console.log(a)

//5.三目运算符 
/*a.格式:
 * 条件语句 ?值1 : 值2;
 * b.结果:
 *判断条件语句的结果是否是true,如果是true,那么表达式的结果就是值1,否则是值2
 */
var b = true ? 10:20;
console.log(b)

//求两个数之间的最大值
var a1 = 80
var a2 = 100
console.log(a1 > a2 ? a1:a2)

//6.运算符的优先级和python基本一样。可以通过括号来改变运算顺序

分支结构

//js中的分之结构有两种:if语句,switch语句
/*1.if语句
 * a.if(条件语句){满足条件要执行的代码块}
 */
var age = 18
if(age>=18){
    console.log('成年')
}

//b.if(条件){语句块1}else{语句块2}
if(age>=18){
    console.log('成年')
}else{
    console.log('未成年')
}

//c.if - else if - else(相当于python中的if-elif-else)
if(age<18){
    Console.log('未成年')
}else if(age<40){
    console.log('青年')
}else{
    console.log('老年')
}

//2.switch语句
/*
 switch(变量){
    case 值1:
        语句1;
        break;
    case 值2:
        语句2;
        break;
    ...
    default:
        语句3;
        break;  
 }
 执行过程:使用变量的值依次和后边每个case后面的值进行判断,看是否相等(是否完全相等)。
 如果相等就执行那个case后面对应的语句。如果前面每个case后面的值都和变量的值不相等,就执行default后边的语句
 */
var score = 10;
switch(score){
    case 1:
        console.log('F');
        break;
    case 10:
        console.log('A+')
        break;
    case 9:
        console.log('A');
        break;
    default:
        console.log('其他');
        break;      
}
console.log('======')

//10分制分数:0-5:不及格,6-7:及格 8-9:良好  10:优秀
score = 9
switch(score){
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        console.log('不及格');
        break;
    case 6:
    case 7:
        console.log('及格');
        break;
    case 8:
    case 9:
        console.log('良好');
        break;   // switch中的break,可以让switch直接结束
    case 10:
        console.log('优秀');
        break;
}

//0-6表示星期1到星期日
var week = 0;
switch(week){
    case 0:
        console.log('周一');
        break
    case 1:
        console.log('周二');
        break;
    case 2:
        console.log('周三');
        break;
    case 3:
        console.log('周四');
        break;
    case 4:
        console.log('周五');
        break;
    case 5:
        console.log('周六');
        break;
    case 6:
        console.log('周日');
        break;
    default:
        console.log('其他情况')
    
}

循环结构

//js中的循环分为for循环和while循环

//1.for循环
//a.for- in (和python中的for循环一样)
// for(变量 in 数组/对象){函数体}
var arr1 =  [1, 2, 'abc']
//x取的是下标
for(var x in arr1){
    console.log(arr1[x])
}

var obj1 = {name:'张三', age:30}
//key拿到的是属性名
for(var key in obj1){
    console.log(key, obj1[key])
}

var str1 = 'abcdef'
for(var x in str1){
    console.log(x, str1[x])
}

//b.for(表达式1;表达式2;表达式3){循环体}
/*执行过程:先执行表达式1,然后再判断表达式2的结果是否是true,如果是true就执行循环体;执行完循环体,再执行表达式3;
 * 执行完表达式3,再判断表达式2的结果是否是true,如果是true又执行循环体;执行完循环体,再执行表达式3;依次类推,
 * 直到表达式2的结果是false,循环就结束
 */
//计算1+2+3+...+100
var sum = 0
for (var i = 1; i < 101 ; i++) {
//  console.log(i)
    sum += i
}
console.log(sum)

var sum1 = 0
var i = 0
for (; i < 101; ) {
    sum1 += i
//  i++;
    i += 1
}
console.log(sum1)

//2.while循环
//a.while(条件语句){循环体} -- 和python一样
var sum2 = 0
var i = 1
while(i <= 100){
    sum2 += i;
    i++;
}
console.log(sum2) 

//b.do-while循环:  do{循环体}while(条件语句);
//执行过程,先执行循环体,然后判断条件是否成立。如果成立再执行循环体。。。
//依次类推,直到条件不成立,循环结束

var sum2 = 0
var i = 1
do{
    sum2 += i;
    i ++;
    
}while(i <= 100);
console.log(sum2) 

//3.break和continue(和python一样)

函数

//1.函数的声明
//function 函数名(参数列表){函数体}
//a.function - 关键字
//b.函数名 - 驼峰式;见名知义
//c.参数:参数可以有默认值,有默认值的参数要写在后面。调用函数传参的时候,是按实参的位置来传参。
//     保证每个参数都有值
//d.函数体: 实现函数的功能。只有在调用的时候才执行

function sum1(num2, num1=1){
    console.log('求两个数的和')
    return num1 + num2
}

console.log(sum1(10,20))
console.log(sum1(10))
//console.log(9/0)

//函数没有return的时候,函数的返回值是undefined
function func1(){
    console.log('我是函数1')
}
console.log(func1()) 


//2.函数的调用
//函数名(实参列表)
//调用过程和python一样

//3.作用域
//全局变量:声明在函数外面的变量(从变量声明到文件结束)
//局部变量:声明在函数里面的变量 (从变量声明到函数结束;函数的参数也是局部变量)


//aaa就是全局变量
var aaa = 10

function func2(){
    //bbb就是局部变量
    var bbb = 100
    console.log(bbb, aaa)
    //函数中可以修改全局变量的值
    aaa = 200
    
    //函数中可以声明函数
    function func22(){
        bbb = 1.1
        console.log(bbb)
    }
}

func2()
//console.log(bbb)
console.log(aaa)

//可以将函数作为变量
var a = func2
a()

//个数不定参数,js不支持

数据结构

//数字、字符串、布尔、列表、对象
//1.数字:包含整数和小数(支持科学计数法)
var num1 = 10
var num2 = new Number()
console.log(num2+10)  

//2.字符串
//a.''和""括起来的字符集
//b.转义字符(和python一样)
//c.字符编码是unicode编码
var str1 = 'abc'
var str2 = "abc"
var str3 = '\n'
var str4 = '\\'

//e.获取字符串长度: 字符串.length
console.log(str1.length)

//f.获取单个字符:字符串[下标]
//下标:1.范围是0 ~ 长度-1  2.如果越界,不报错,但是结果是undefined
//js中的字符串不能切片
console.log(str1[0])

//g.运算符
//js中字符串只支持+,不支持*
// 字符串1 + 字符串2 -- 拼接两个字符串
// js中字符串可以和其他任何数据进行加操作,其效果都是字符串连接(会将其他数据转换成字符串)
console.log('123'+'abc', 'abc'+100) 

//h.字符串相关方法(查)
var strstr = 'abc123'
var re = strstr.replace(/\d+/i,'ooo')
console.log(re)


//3.对象,构造方法(类)
var obj1 = {name:'YuTing', age:18}
console.log(obj1.name, obj1['name']) 

//声明构造方法
function Person(name='', age=0, sex=''){
    this.name = name
    this.age = age
    this.sex = sex
}

var p1 = new Person()
p1.name = 'mmm'
p1.age = 20
console.log(p1, typeof(p1))

web方向:php、java、python,服务端的语言
客户端===服务端

1. js引入方式和打印方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- <script src="js.js"></script> -->
</head>
<body>
    <a href="javascript:alert('集合,准备团战')">百度一下</a>
    <div style="width:200px; height:200px; background-color:red" onclick="alert('等等我,马上到')"></div>
</body>
</html>
<script>
    // alert('猥琐发育,别浪')
    // document.write('<b>注意,我来抓人了</b>')
</script>
2. 函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    // var a = '李白'
    // b = '杜甫'
    // // alert(b)
    // function demo() {
    //     c = '白居易'
    //     alert(c)
    //     // alert(b)
    // }
    // demo()
    // alert(c)

    var m = 100
    var n = 200

    function demo() {
        // var m
        // var n
        var m = 300
        var n = 400
        console.log(m, n)
    }

    demo()
    console.log(m, n)
</script>

//封闭
<script>
    // var a = function () {
    //     alert('天青色等烟雨,而我在等你')
    // }
    // a()

    // var a = function () {
    //     alert('这是一个函数')
    // }
    // a()
    // var b = a
    // b()

    // function demo() {
    //     alert('哈哈哈')
    // }
    // var a = demo
    // a()

    function add(m, n) {
        return m + n
    }
    function sub(m, n) {
        return m - n
    }

    function cacl(m, n, fn) {
        return fn(m, n)
    }

    // alert(cacl(100, 200, sub))
    alert(cacl(100, 200, function (m, n) {
        return m * n
    }))

    // (function (m, n) {
    //     alert('炊烟袅袅升起,隔江千万里===' + m + n)
    // })('周杰伦', '双节棍')
</script>

3. 数组
<script>
var arr1 = [1, '周杰伦', 2, '王力宏']
arr1['name'] = '狗蛋'
arr1['height'] = 180
// var arr = []
// var arr2 = new Array()

// 通过下标进行访问,下标从0开始
// alert(arr1[1])
// alert(arr1)
// alert(arr1['name'])
// console.log(arr1[4])
// 遍历数组
// for (var i = 0; i < arr1.length; i++) {
//     console.log(arr1[i])
// }

// for (var i in arr1) {
//     console.log(arr1[i])
// }

string1 = '12345,上山打老虎'
for (var i = 0; i < string1.length; i++) {
    console.log(string1[i])
}
</script>
4. 对象
<script>
/*
function Person(name, age, height, weight) {
    this.name = name
    this.age = age
    this.height = height
    this.weight = weight
    this.say = function () {
        console.log('我的名字叫做' + this.name + '==我的年龄为' + this.age + '==我的身高为' + this.height + '==我的体重为' + this.weight)
    }
}
obj = new Person('黄晓明', 40, 150, 200)
obj.say()
*/

// 创建对象方式2
// obj = new Object()
// obj.name = '黄晓明'
// obj.age = 40
// obj.height = 150
// obj.say = function () {
//     alert('haha')
// }
// console.log(obj)

// 创建对象方式3
// json格式,前后端交互使用的格式,json格式在js里面原生支持
obj = {name: '王宝强', age: '36', wife: '马蓉蓉'}

// 没有这种写一个class,然后里面写属性写方法这种特点了
// console.log(obj.name)
// console.log(obj['name'])
// 将js里面的对象转化为json格式字符串
string = JSON.stringify(obj)
// console.log(typeof(string))
// js如何将json格式字符串转化为js对象
// ming = JSON.parse(string)
ming = eval('(' + string + ')')

console.log(ming)
</script>
5. 常用对象和函数
<script>
// 将字符串转化为整型
/*
var string = 'a100px'
var string2 = 'b200'
var num1 = parseInt(string)
var num2 = parseInt(string2)
if (num1 == NaN) {
    console.log('相等')
} else {
    console.log('不相等')
} */
// var num = parseInt(string) + 100
// console.log(parseInt(string))
// var num = parseInt(string) + 100
// var string = num + 'px'

// var string = '3..14.15lalala'
// console.log(parseFloat(string))
// console.log(parseInt(string))

// console.log(Math.abs(-200))
// console.log(Math.ceil(3.14))
// console.log(Math.floor(3.14))
// console.log(Math.max(1, 200, 900, 56))
// console.log(Math.pow(2, 3))
// console.log(Math.random())

// console.log(Math.round(3.54))

// string = 'i love you BABY, you love me'

// console.log(string.split(' '))

// console.log(string.charAt(0))
// console.log(string[0])

// console.log(string.indexOf('love'))
// console.log(string.lastIndexOf('love'))
// console.log(string.substr(2, 4))
// console.log(string.replace('love', 'hate'))

// console.log(string.toLowerCase())

// console.log(String.fromCharCode(97))

// var arr = ['柳岩', '高圆圆', '韩红', '赵丽颖', '杨幂']

// console.log(arr.slice(1, 3))
// console.log(arr.reverse())
// console.log(arr.join('*'))
// arr.shift()
// arr.unshift('赵丽颖')


// arr.push('李宇春')

// console.log(arr)
// console.log(arr.pop(2))
// console.log(arr)

// var arr = ['baby', 'curry', 'anglebaby', 'love', 'taikongyi', 'anglebaby']

// var arr = [100, 15, 200, 29, 300, 56]

// console.log(arr.sort(function (a, b) {
//     return a > b
// }))

// 创建当前时间的时间对象
d = new Date()
// 根据指定的时间戳创建时间对象
d = new Date(1534750144520)
// 根据时间字符串创建时间对象
d = new Date('2018/8/20 15:29:04')
// 根据年月日时分秒值创建对象
d = new Date(2018, 7, 20, 15, 29, 4)
// console.log(d)
// console.log(d.getDate())
// console.log(d.getDay())
// console.log(d.getMonth())
// console.log(d.getFullYear())
// console.log(d.getHours())
// console.log(d.getMinutes())
// console.log(d.getSeconds())
// console.log(d.getTime())
</script>

<!-- lt = ['hello', 'baby']

string = '*'.join(lt) -->
6. js简单演示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试</title>
    <link id="lk" rel="stylesheet" href="yellow.css">
</head>
<body>
    <button onclick="document.getElementById('lk').href = 'red.css'">点我变成红色</button>
    <button onclick="document.getElementById('lk').href = 'yellow.css'">点我变成黄色</button>
</body>
</html>
7. 获取对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试</title>
</head>
<body>
    <div id="libai">日照香炉生紫烟,遥看瀑布挂前川</div>
    <div class="dufu">会当凌绝顶,一览众山小</div>
    <div class="dufu">安得广厦千万间,大庇天下寒士俱欢颜</div>
</body>
</html>
<script>
    // div1 = document.getElementById('libai')
    // console.log(typeof(div1))
    // div2 = document.getElementsByClassName('dufu')
    div3 = document.getElementsByTagName('div')
    console.log(div3[2])
</script>
8. 常用事件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div style="width:200px; height:200px; background-color:red" onmouseover="alert('明天我要嫁给你啦')"></div>
    <div style="width:200px; height:200px; background-color:green" onmouseout="alert('后天我们要结婚')"></div>
    <div style="width:200px; height:200px; background-color:blue" onmouseup="alert('后天我们要结婚')"></div>
    <div style="width:200px; height:200px; background-color:gray" onmousedown="alert('后天我们要结婚')"></div>
    <div style="width:200px; height:200px; background-color:pink" onmousemove="console.log('后天我们要结婚')"></div>
    <div style="width:200px; height:200px; background-color:purple" onclick="alert('后天我们要结婚')"></div>
    <div style="width:200px; height:200px; background-color:orange" ondblclick="alert('后天我们要结婚')"></div>
    <input type="text" onblur="console.log('我失去了焦点,生活没有意义了')" onfocus="console.log('得到焦点,得到了全世界')"/>
</body>
</html>

9. 获取、设置属性和内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="bai" class="li" name='wang' style="width:200px; height:200px; background-color:gold"><b>李白乘舟将欲行,忽闻岸上踏歌声,桃花潭水深千尺,不及汪伦送我情</b></div>
    <a href="www.baidu.com" id="lala"></a>
</body>
</html>
<script>
var odiv = document.getElementById('bai')
var oa = document.getElementById('lala')
// console.log(odiv.style.height)
// console.log(odiv.style.backgroundColor)

// console.log(odiv.innerHTML)
// console.log(odiv.innerText)
// console.log(odiv.style.width)
// console.log(odiv.style['width'])
// console.log(odiv['style']['width'])

obj = {name: '王宝强', age: 30}
console.log(obj.name, obj['name'])
for (var i in obj) {
    console.log(obj[i])
}
</script>
10. onload函数
practice
  1. 判断一个数是奇数还是偶数
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    </body>
</html>
<script type="text/javascript">
    function fun(n){
        if(n%2==0){
            console.log('是偶数!')
        }else{
            console.log('是奇数')
        }
    }
    fun(56)
    fun(43)
</script>
  1. 给一个年份,判断是否是闰年
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(y){
        if(y%400==0||(y%100!=0&&y%4==0)){
            console.log(y+'年是闰年!')
        }else{
            console.log(y+'年不是闰年!')
        }
    }
    fun(2012)
    fun(2000)
    fun(1900)
</script>
  1. 给一个数n,计算n的阶乘
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(n){
        if(n==1)
            return 1
        return n*fun(n-1)
    }
    console.log(fun(10))
</script>
  1. 打印99乘法表
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(){
        document.write("<table>")
        for(var i = 0; i < 9; i++) {
            document.write("<tr>")
            for (var j = 0; j <= i; j++) {
                document.write("<td style='border: 1px solid;'>"+(i+1)+" * "+(j+1)+" = "+(i+1)*(j+1)+"</td>")
            }
            document.write("</tr>")
        }
        document.write("</table>")
    }
    fun()
</script>
  1. 计算1-1/2+1/3-1/4 … 1/100的和
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(){
        temp = 1
        sum = 0
        for(var i = 1; i <= 100; i++){
            sum += 1/i*temp;
            temp *= -1
        }
        alert(sum)
    }
    fun()
</script>
  1. 给一个n,求1!+2!+3!+4!+5!...+n!
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(n){
        function fun1(m){
            if(m==1)
                return 1
            return m*fun1(m-1)
        }
        sum = 0
        for(var i = 0; i < n; i++){
            sum += fun1(i+1)
        }
        alert(sum)
    }
    fun(4)
</script>
  1. 找到所有的水仙花数
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(){
        for(var i = 100; i < 1000; i++)
            if(Math.pow((i%10),3)+Math.pow(parseInt(i%100/10),3)+Math.pow(parseInt(i/100),3)==i)
                document.write(i+"   ")
    }
    fun()
</script>
  1. 输入三个数,找到其中最大的,用一句话写出来
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(a,b,c){
        document.write(a+", "+b+", "+c+"三个数的最大值为:"+Math.max(a,b,c))
    }
    fun(3,1,8)
</script>
  1. 给一个数组,找到其中最大值和最小值
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(arr){
        arr.sort(function fun(a,b){return a>b})
        alert(arr[0])
    }
    arr = [3,5,2,7,4,12,7]
    fun(arr)
</script>
  1. 用while打印十行十列表格,表格里面写
    1-100,并且隔行变色
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(arr){
        var i = 1;
        document.write("<table border='1'>");
        while(i<=100){
            if(i%10==1){
                document.write("<tr><td>"+i+"</td>");
                i++;
                continue;
            }
            if(i%10==0)
            {
                document.write("<td>"+i+"</td></tr>");
                i++;
                continue;
            }
            document.write("<td>"+i+"</td>");
            i++;
        }
        document.write("</table>");
    }
    arr = [3,5,2,7,4,12,7]
    fun(arr)
</script>
  1. 自己实现随机 a, b 之间的整型
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        
    </body>
</html>
<script type="text/javascript">
    function fun(a, b){
        return parseInt((Math.max(a,b)-Math.min(a,b))*Math.random())+Math.min(a,b)
    }
    for(var i = 0; i < 20; i++)
        console.log(fun(1,20))
</script>
上一篇 下一篇

猜你喜欢

热点阅读