基本数据类型
number
boolean
String
被单引号或者双引号引起来的都叫做字符串
// 字符串的拼接const name="黎明";const age=18;console.log(`${name}的年龄是${18}`) //模板字符串console.log(name+"的年龄是"+age)//大小写转换const str="heLlo"console.log(str.toLocaleUpperCase())console.log(str.toLocaleLowerCase())//字符串的截取const s="hello word "console.log(s.substring(0,4))const cazz="一年级,二年级,三年级,"//字符串分割到数组中console.log(cazz.split(','))//是否包含某个字符串console.log(cazz.includes("一年级"))//是否以某个字符开头console.log(cazz.startsWith("一"))////是否以某个字符结尾console.log(cazz.endsWith("级"))
特殊数据类型
null:空
undefind:定义未赋值,系统默认的值
NaN:本应该是数字,但不是一个数字
查看类型的方式
使用typeof可以查看数据类型
const test=2;console.log(typeof test)
类型转化
const a=3
console.log(a.toString()) //转化成字符串
console.log(String(a)) //转化成字符串
console.log(parseInt(1.2)) //转化成整数
console.log(parseInt('1.2sdfsd')) //自动截取字母之前的数字
console.log(parseFloat('1.23px')) //自动截取浮点数
console.log(parseInt('as1.2')) //NaN类型
console.log(Number('12')) //转化成数字
console.log('1.2' - 0) //利用算数运算(- * /)隐式转化
console.log(Boolean(NaN)) //false
console.log(Boolean('')) //false
console.log(Boolean(null)) //flase
console.log(Boolean(undefined)) //flase
console.log(Boolean('dddd')) //true
console.log(Boolean(12))//true
变量的定义
以下列出三种定义方式,以及他们各自的特点,程序的健壮性以此降低
常量
使用const定义,表示这个值是不能被改变的
const test='hello word'
变量
使用let定义的是一个变量,它是一个局部变量,在一个JavaScript中可以出现多个相同的变量名
let test ='hello word'
使用var定义表示这是一个全局变量,在一个JavaScrip标签中只能出现一个变量名。
var test='hello world'
数组
数组的定义有两种方式
基本数据类型定义
结构体定义
//数组
var arr= new Array(); //创建空数组
var arr=[]; //创建空数组
const arr = ['a', 'b', 'c', 4];
const arr1 = new Array(1, 2, 3, 4)//结构体定义
arr.push(2)//向结尾添加元素
arr.unshift(1)//向开头添加元素
arr.pop();//移除最后一个元素
console.log({ arr })
console.log({ arr1 })
console.log(Array.isArray(arr))//判断是不是数组
console.log(arr.indexOf('a'))//元素所在的下标
对象
定义方式
var obj={}; //定义一个空对象
var obj=new Object() //new一个空对象
function Presons(name,age,sex){ //构造函数
this.age=age;
this.name=name;
this.sex=sex;
}
console.log(new Presons('张三',12,'男')) //对象
//对象
const person={
names:'zl', //属性:采用键值对
age:18,
hobbies:['music','movies'], //数组
fun:function(){ //方法:冒号后跟匿名函数
console.log('hhh')
} ,
address:{
city:'xa',
state:'yt'
}
}
console.log({person})
console.log(person.address.city) //获取属性的值
console.log(person['age']) //获取属性的值
person.fun(); //调用对象的方法
console.log(person.hobbies[1])
//解构表达式:以某种方式从对象中获取属性
const {names,address}=person;
console.log(names)
console.log(address.state)
//添加属性
person.email='...qq.com'
//数组对象
const persons=[
{
id:1,
name:'zs'
},
{
id:2,
name:'zd'
},
{
id:3,
name:'zf'
}
]
console.log(persons)
JSON
json和对象的格式有些类似,在格式:JSON的属性名需要双引号引起来的,包括值也需要双引号引起来
//对象
const persons=[
{
id:1,
name:'zs'
},
{
id:2,
name:'zd'
},
{
id:3,
name:'zf'
}
]
console.log(persons)
const personsJson=JSON.stringify(persons) //将对象转化json格式
console.log({personsJson})
