1. 变量
// Javascript常用变量类型
// numbers,string,boolean,
// Object:Array,Undefined,null
// const 常量不能修改
// let和var 变量可修改
const name ="Tom";
const age = 22;
const rating = 4.5;
const isCool = true;
// Object:
const x = null;
let z = [1,2,3];
const y = undefined;
console.log('typeof name:',typeof name);
console.log('typeof isCool:',typeof isCool);
console.log('typeof x:',typeof x);
console.log('typeof y:',typeof y);
console.log('typeof z:',typeof z);
console.log('x:',x);
console.log('y:',y);
console.log('z:',z);
console.log('z[0]:',z[0]);
// let 可以改变
z = [6,7,'8'];
console.log('z:',z);
2. 字符串操作
// 字符串操作 String
console.log('----------------String-------------');
// 字符串拼接
console.log('My name is ' + name, 'and I am ' + age);
// Linux Shell相同
console.log(`My name is ${name} and I am ${age}`);
// 属性没有括号,方法有括号
console.log('name.length:',name.length);
let name_m= 'hello world';
// 字符串全部改为大写
console.log('name_m.toLocaleUpperCase():',name_m.toLocaleUpperCase());
// h w 改为大写
console.log('name_m.substring(0,5).toLocaleUpperCase():',name_m.substring(0,5).toLocaleUpperCase());
// 字符串分割同Python
const name_s = 'hello world';
console.log("name_s.split(' '):",name_s.split(' '));
3. 数组操作
// 数组操作 Array
console.log('--------------------Array--------------');
const f = ['apples','oranges','pears'];
console.log('f[1]:',f[1]);
// 数组可以添加值
f[3]='grapes';
// push末尾添加
f.push('egg');
// unshift头部添加
f.unshift('ihave');
console.log('f:',f);
// pop尾部删除
f.pop();
console.log('f:',f);
// 判断是不是数组
console.log('Array.isArray(f):',Array.isArray(f));
// 查询数组索引
console.log("f.indexOf('grapes'):",f.indexOf('grapes'));
// 最后一个值的索引是-1
console.log("f.indexOf('egg'):",f.indexOf('egg'));
4. 对象操作
// 对象的操作
console.log('----------Object----------');
const person ={
firstName : 'Tom',
lastName : 'Doe',
age : 30,
hobbies : ['music','movies','sports'],
address :
{
street : '50 main st',
city : 'Boston',
state : 'MA'
}
}
console.log('person:',person);
console.log("person['firstName']:",person['firstName']);
console.log('person.hobbies[0]:',person.hobbies[0]);
console.log('person.address.city:',person.address.city);
// 暴露出来变量
const
{
firstName,
lastName,
address:
{city}
} = person;
console.log('firstName:',firstName);
console.log('city:',city);
person.email='a@a.com'
console.log('person.email:',person.email);
const todos =
[
{
id : 1,
text : 'Take out trash',
inCompleted : true
},
{
id : 2,
text : 'Meeting with boss',
inCompleted : true
},
{
id : 3,
text : 'Dentist appt',
inCompleted : false
},
];
console.log('todos:',todos);
console.log('todos[1].id:',todos[1].id);
// 转换JSON
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
END