JS基础学习笔记

110 阅读2分钟

配置环境

  • 安装node 、vsCode
  • vsCode安装 Live Server 插件:运行html文件到浏览器上,可通过js控制台查看输出
  • vsCode安装 Run Code 插件:直接编译js文件,在下方控制台查看输出

变量与常量

  • var 全局
  • let 变量
  • const 常量

字符串

//定义
const msgs = new String();
const msgs = 'Hello World WKW';
//输出
console.log(msgs); 
//长度
msgs.length
//取第一个元素
msgs[0]
//转换大小写
msgs.toUpperCase()
msgs.toLowerCase()
//截取
msgs.substring(0,5)
//分隔 转换成 数组
msgs.split(' ')
//拼接
let m = msgs + "拼接";
//查询子串位置
msgs.indexOf("Hellow")

数组

//定义
const arr = new Array();
const arr1 = [];
const arr2 = ["11","22","33"];
//数组取值
console.log(arr2[1]); 
//尾部追加元素
arr2.push("44"); 
//删除末尾元素
arr2.pop(); 
//头部添加元素
arr2.unshift("00"); 
//判断类型
console.log(Array.isArray(arr2)); 
//获取元素索引
console.log(arr2.indexOf("11")); 
//转换成 字符串
var a = [1,2,3,4,5,6,7,8,9,0];  //定义数组
var s = a.toString();  //把数组转换为字符串
console.log(s);  //返回字符串“1,2,3,4,5,6,7,8,9,0”

var a = [1,2,3,4,5,6,7,8,9,0];  //定义数组
var b = \[1,2,3,4,5,6,7,8,9,0];  //定义数组
var s = a + "," + b;  //数组连接操作
console.log(s);  //返回“1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0”

var a = \[1,\[2,3],\[4,5]],\[6,\[7,\[8,9],0]]];  //定义多维数组
var s = a.toString();  //把数组转换为字符串
console.log(S);  //返回字符串“1,2,3,4,5,6,7,8,9,0”

对象/字典

//定义
const person = {
    firstName: "First",
    lastName: "Last",
    age: 22,
    hobbies: ["music","movies","football"],
    address: {
        street: "sssss",
        city: "jinan",
        state: "shandong"
    }
};
//追加
person.email = "5555@163.com";

//转换成json串
const toJson = JSON.stringify(person);
console.log(toJson);
//输出{"firstName":"First","lastName":"Last","age":22,"hobbies":["music","movies","football"],"address":{"street":"sssss","city":"jinan","state":"shandong"},"email":"5555@163.com"}

if 条件语句

var x = 10;
var y = 20;
if (x == 10) {
console.log("true");
} else {
console.log("false");
}

if (x > y) {
console.log("true");
}

if (x == 10 && y == 20) {
console.log("true");
}

if (x == 10 || y == 20) {
console.log("true");
}

//三目运算
const color = x == 10 ? 'red' : 'blue' ;

switch 条件语句

switch (color) {
    case "red":
        console.log("color: red");
        break;
    case "blue":
        console.log("color: blue");
        break;
    default:
        console.log("color: other");
        break;
}

循环

for (let i = 0; i < 10; i++) {
    console.log(i);
}

let a = 10;
while (a < 20) {
    console.log(a);
    a++;
}

不看了,直接卷vue去