javascript
小试牛刀——JS基础
JS(JavaScript)控制網(wǎng)頁的行為。JS是互聯(lián)網(wǎng)中最流行的腳本語言,網(wǎng)頁、小程序、app等。
1.JS是腳本語言。
2.js是輕量級的編程語言。
3.JS是可插入HTML頁面的代碼。
4.所有現(xiàn)代瀏覽器均可執(zhí)行JS代碼
JS代碼可以借助script標(biāo)簽放到head或者body標(biāo)簽中。
以下為代碼示例
修改span標(biāo)簽內(nèi)容,
1)先加入點擊事件onclick,
2)確定位置:document.getElementById(‘name’),固定寫法,我們記住就好
3)設(shè)置標(biāo)簽中的文本內(nèi)容:添加 innerText
4)設(shè)置內(nèi)容為document.getElementById(‘info’).value,第一個input.
同理,我們修改圖片時需要加 src,修改樣式時需要加 style 。
<img src="./img/1.png" alt="" id="photo"> <input type="submit" value="更改圖片" onclick="document.getElementById('photo').src = './img/2.png'"><p id="style">段落</p> <input type="submit" value="華麗的" onclick="document.getElementById('style').style = 'color:pink;font-size:20px;'"> <input type="submit" value="樸素的" onclick="document.getElementById('style').style = ''">效果如圖
| 圖1 樸素 | 圖2 華麗 |
在JS中插入html代碼
<script type="text/javascript">titles = ['四川','云南','貴州','湖北']for (x in titles){title = titles[x]html_str = "<span id='one'>" + title + "</span><span>|</span>"document.write(html_str)}document.getElementById('one').style = 'color:red;' </script>通過前面幾個代碼,我們對JS的作用更為了解,接下來我詳細(xì)地介紹關(guān)于JS的一些基礎(chǔ)知識。
1.定義變量
變量名 = 變量值(全局變量) var 變量名 = 值 (函數(shù)中的局部變量) let 變量名 = 值({}中的局部變量) const 變量名 = 值(常量)2.運算符
數(shù)學(xué)運算符:+、-、*、/、%、** 比較運算符:>、<、>=、<=、==、!=、===、!== 賦值運算符:=、+=、-=、*=、/=、**=、%= 邏輯運算符:&&(邏輯與)、||(邏輯或運算)、!(邏輯非運算)3.分支結(jié)構(gòu)
單分支
if(條件語句){代碼塊 }else{代碼塊 }多分支
if(條件){代碼塊 }else if(條件){代碼塊 }else if(條件){代碼塊}else{}else可以省略不寫
三目運算符
4.循環(huán)
for-in循環(huán)
for(變量 in 序列){代碼塊 }while循環(huán)
while(條件語句){代碼塊 }傳統(tǒng)for循環(huán)
for(表達(dá)式1;表達(dá)式2;表達(dá)式3){代碼塊 }傳統(tǒng)for循環(huán)改while循環(huán)
表達(dá)式1 while(表達(dá)式2){代碼塊表達(dá)式3 }5.函數(shù)
定義:
將重復(fù)的代碼封裝起來,以便重復(fù)調(diào)用。function 函數(shù)名(形參列表){函數(shù)體 }調(diào)用
函數(shù)名(實參列表)作用:
1.降低代碼的冗余度。 2.將執(zhí)行某一功能的代碼封裝起來,更容易讓人理解。測試一下掌握程度吧!
使用while循環(huán)輸出 0~100內(nèi)所有3的倍數(shù)
i = 1 while(i <= 100){if(i % 3 === 0){console.log(i)}i += 1 }使用循環(huán)計算1*2*3*4*…*10的結(jié)果
i = 1 j = 1 while(i <= 9){i += 1j *= i } console.log(j)統(tǒng)計一個字符串中數(shù)字的個數(shù)(使用函數(shù)進(jìn)行封裝)
function num_str(str){tot = 0for(i in str){if(str[i] >= 0 && str[i] <= 9){tot += 1}}console.log(tot) } num_str('woai1sdfgh876543223')計算所有學(xué)生平均分
stu = [{name: '大黃', age: 27, score: 60},{name: '小明', age: 18, score: 89},{name: '張三', age: 23, score: 92},{name: '小花', age: 20, score: 71},{name: '小紅', age: 30, score: 84} ] b = 0 for(x in stu){a = stu[x].scoreb+= amean = b / 5 } console.log(mean)求斐波那契數(shù)列列中第n個數(shù)的值:1,1,2,3,5,8,13,21,34… (這兒的n可以是任意正整數(shù),可以通過輸入來確定)
function n_val(n){if(n === 1 | n === 2){console.log(1)}else{f1 = 1f2 = 1for(i=3;i<=n;i++){f = f1 + f2f1 = f2f2 = f}return console.log(f2)} } n_val(1),n_val(2),n_val(3),n_val(4),n_val(5),n_val(6)總結(jié)
以上是生活随笔為你收集整理的小试牛刀——JS基础的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Aruba7010 默认密码_【对讲机的
- 下一篇: spring boot Actuator