javascript
小试牛刀——JS基础
JS(JavaScript)控制網頁的行為。JS是互聯網中最流行的腳本語言,網頁、小程序、app等。
1.JS是腳本語言。
2.js是輕量級的編程語言。
3.JS是可插入HTML頁面的代碼。
4.所有現代瀏覽器均可執行JS代碼
JS代碼可以借助script標簽放到head或者body標簽中。
以下為代碼示例
修改span標簽內容,
1)先加入點擊事件onclick,
2)確定位置:document.getElementById(‘name’),固定寫法,我們記住就好
3)設置標簽中的文本內容:添加 innerText
4)設置內容為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的作用更為了解,接下來我詳細地介紹關于JS的一些基礎知識。
1.定義變量
變量名 = 變量值(全局變量) var 變量名 = 值 (函數中的局部變量) let 變量名 = 值({}中的局部變量) const 變量名 = 值(常量)2.運算符
數學運算符:+、-、*、/、%、** 比較運算符:>、<、>=、<=、==、!=、===、!== 賦值運算符:=、+=、-=、*=、/=、**=、%= 邏輯運算符:&&(邏輯與)、||(邏輯或運算)、!(邏輯非運算)3.分支結構
單分支
if(條件語句){代碼塊 }else{代碼塊 }多分支
if(條件){代碼塊 }else if(條件){代碼塊 }else if(條件){代碼塊}else{}else可以省略不寫
三目運算符
4.循環
for-in循環
for(變量 in 序列){代碼塊 }while循環
while(條件語句){代碼塊 }傳統for循環
for(表達式1;表達式2;表達式3){代碼塊 }傳統for循環改while循環
表達式1 while(表達式2){代碼塊表達式3 }5.函數
定義:
將重復的代碼封裝起來,以便重復調用。function 函數名(形參列表){函數體 }調用
函數名(實參列表)作用:
1.降低代碼的冗余度。 2.將執行某一功能的代碼封裝起來,更容易讓人理解。測試一下掌握程度吧!
使用while循環輸出 0~100內所有3的倍數
i = 1 while(i <= 100){if(i % 3 === 0){console.log(i)}i += 1 }使用循環計算1*2*3*4*…*10的結果
i = 1 j = 1 while(i <= 9){i += 1j *= i } console.log(j)統計一個字符串中數字的個數(使用函數進行封裝)
function num_str(str){tot = 0for(i in str){if(str[i] >= 0 && str[i] <= 9){tot += 1}}console.log(tot) } num_str('woai1sdfgh876543223')計算所有學生平均分
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)求斐波那契數列列中第n個數的值:1,1,2,3,5,8,13,21,34… (這兒的n可以是任意正整數,可以通過輸入來確定)
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)總結
以上是生活随笔為你收集整理的小试牛刀——JS基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Aruba7010 默认密码_【对讲机的
- 下一篇: spring boot Actuator