JavaScript(1)--基礎
阿新 • • 發佈:2018-11-08
js設定的位置
- 在渲染元素之前:需要js對元素進行調整和配置等影響元素的渲染的程式碼
- 在渲染元素之後:通過js對元素進行修改等操作
- 通過引入js檔案的方式載入js
語法
- 宣告區域性變數
var a = 10;
var b = 20;
var c = 30;
- 輸出日誌資訊,類似於print()
console.log(a,b,c)
- if 條件判斷
if (a > b){ console.log('a是大於b'); }else{ console.log('a小於等於b'); }
- &&:且 //或者
if (a == 10 && b == 20){
console.log('a=10且b==20');
}else if(c == 100){
console.log('c=100');
}else{
console.log('其他情況');
}
- for迴圈
array = [1,2,3,4,5,6,7,8,9,10]; for (var i = 0; i < array.length; i++){ //i < array.length: 只要這個條件成立,迴圈會繼續執行,反之,迴圈停止; //每次迴圈i的值+1; console.log(i); }
- 泛型遍歷for in
for (res in array){
console.log('res=',res)
}
- while迴圈
while (a<30){
console.log('a=',a)
}
- 字典
dic = {"name": "張三", "age": 20};
console.log(dic['name'], dic['age']);
- 函式的宣告 function {}
function eat(name){
console.log(name)
}
- 匿名函式的宣告
var f =function(){
console.log('執行了匿名函式')
}
- 呼叫eat函式和匿名函式
eat('米飯')
f()
- 宣告並自呼叫的函式:
#結構
(function(){console.log('自呼叫')})();
#引數n
(function (n) {
console.log('自呼叫',n)
})(100);