JavaScript 是 web 开发人员必须学习的 3 门语言中的一门:
- HTML 定义了网页的内容
- CSS 描述了网页的布局
- JavaScript 控制了网页的行为
以下代码是学习四十分钟JavaScript快速入门做的记录
还可以借鉴JavaScript 教程
// 变量与常量
// let , const
// let 变量
// const 常量
let age = 30;
age = 31;
console.log(age);
//原生数据类型
// String,Number,Boolean,null,undefined
const username = "John";
const age2 = 30;
const rate = 4.5;
const isCool = true;
const x = null;
const y = undefined;
let z;
console.log(typeof rate);
console.log(typeof username);
console.log(typeof z);
//模板字符串
//连接
console.log("My name is "+username+"and I am " + age);
const hello = `My name is ${username} and I am ${age}`;
console.log(hello);
//字符串的内置方法
const s = "Hello world!"
console.log(s.length);
console.log(s.toUpperCase());//大写
console.log(s.toLowerCase());//将字母全部小写
console.log(s.substring(0,5));//分割
console.log(s.substring(0,5).toUpperCase());//分割+大写
console.log(s.split(""))
const t = "technology,computers,it,code";
console.log(t.split(","));//使用,分割
//数组
const numbers = new Array(1,2,3,4,5);
console.log(numbers);const fruits = ["apples","oranges","pears",10,true];
fruits[6] = "grapes";
fruits.push("mangos");//数组末尾添加一个元素
fruits.unshift("王");//数组首添加一个元素
fruits.pop();//删除数组末尾元素
console.log(fruits);
console.log(Array.isArray(fruits));
console.log(Array.isArray('ok'));
console.log(fruits[2]);
console.log(fruits.indexOf("王"));
console.log(fruits.indexOf("王")+1);const person = {firstName:"John",lastName:"Doe",age:30,address:{street:"50 main st",city:"Boston",state:"A" },
};
console.log(person.firstName,person.lastName);
console.log(person.address.city);const {firstName,lastName,address:{city},
} = person;
console.log(lastName,city);
//添加新的属性
person.email = "John@gmail.com";
console.log(person);
//对象数组和JSON
const todos = [{id:1,text:"Take out trash",isCompleted:true,},{id:2,text:"Meeting",isCompleted:true,},{id:3,text:"invent app",isCompleted:false,},
];
console.log(todos[0]);
console.log(todos[2].text);const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
//if条件语句
const b = 20;
if(b === 10){console.log("b is 10")
}else if(b > 10){console.log("b is 大于 10")
}else{console.log("b is not 10")
}
// ||或&&与
// 三目运算符
const e = 10;
const color = e >7 ?"grenn":"blue";
console.log(color);//switch语句
switch(color){case "red":console.log("进入red");break;case "blue":console.log("进入蓝色");break;default:console.log("都不是");
}
//For
for(let i = 0; i <= 10;i++){// console.log(i);console.log(`For Loop Number:${i}`);
}
//while
let i = 0;
while(i < 10){console.log(`For Loop Number:${i}`);i++;
}
//使用对象数组作为循环的条件
for(let i = 0;i < todos.length;i++){console.log(`For Loop Number:${i} `+ todos[i].text);
}
for(let todo of todos){console.log(todo.text+todo.id);
}