0
点赞
收藏
分享

微信扫一扫

前端基础(二十四):label语句、with语句、JSON、生成器、解析赋值、历史状态管理、将页面可编辑


label语句

let data = { a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' }

// break 跳出switch循环,但是for循环继续
// no a => b => no c => no d => no e
for (key in data) {
switch (key) {
case "b":
console.log(key);
break;
default:
console.log('no', key);
}
}

// label语句 当满足条件后跳出for循环
// no a => b
outloop: for (key in data) {
switch (key) {
case "b":
console.log(key);
break outloop;
default:
console.log('no', key);
}
}

width 将作用域设置到特定的对象中

a = 'AAA';
b = 'BBB';
let data = { a: 'aaa' }
with(data){
console.log(a); // aaa
console.log(b); // BBB
}

JSON stringify

var foo = { name: "Lee", age: 24, sex: '男' };
var jsonString = JSON.stringify(foo, (key, value) => {
console.log(key, value); // name Lee --- age 24 --- sex 男
if (typeof value === 'number') {
return undefined
}
return value
});
console.log(jsonString); // {"name":"Lee","sex":"男"}

const students = [
{
name: 'akira',
score: 100,
},
{
name: 'John',
score: 60,
},
{
name: 'Jane',
score: 90,
}
];
let jsonStudents = JSON.stringify(students, (key, value) => {
if (key === 'score') {
if (value === 100) {
return 'S';
} else if (value >= 90) {
return 'A';
} else if (value >= 70) {
return 'B';
} else if (value >= 50) {
return 'C';
} else {
return 'E';
}
}
return value;
});
console.log(jsonStudents); // [{"name": "akira","score": "S"},{"name": "John","score": "C"},{"name": "Jane","score": "A"}]

let jsonStudentsNames = JSON.stringify(students, ['name']);
console.log(jsonStudentsNames); // [{"name":"akira"},{"name":"John"},{"name":"Jane"}]

JSON parse

let json = '[{"name": "akira","score": "S"},{"name": "John","score": "B"},{"name": "Jane","score": "A"}]';
let arr = JSON.parse(json, (key, value)=>{
if(key === 'score'){
switch(value){
case 'S':
return '优';
case 'A':
return '甲';
case 'B':
return '乙';
}
}
return value;
})
console.log(arr); // [{name: "akira", score: "优"},{name: "John", score: "乙"},{name: "Jane", score: "甲"}]

生成器

function* addCount(){
let count = 0;
while (true) {
yield count++
}
}
let add = addCount();

console.log(add.next()); // {value: 0, done: false}
console.log(add.next()); // {value: 1, done: false}
console.log(add.next()); // {value: 2, done: false}

解析赋值

var [name, age] = ['Lee', 24];
console.log(name);
console.log(age);

交换

let a = 1;
let b = 2;
[a, b] = [b, a]
console.log(a); // 2
console.log(b); // 1

对象解析赋值

let obj = {
name: 'Lee',
}

let {name} = obj; // => let {name: name} = obj;
console.log(name); // Lee

let {name: a} = obj;
console.log(a); // Lee

let obj = {
name: 'Lee',
age: 24
}
let {name: _name, age: _age} = obj;
console.log(_name); // Lee
console.log(_age); // 24

pushState popstate

window.onload = function () {
pushHistory();
setTimeout(function () {
window.addEventListener('popstate', function (event) {
let e = event || window.event;
console.log(e);
}, false);
}, 100);
}
function pushHistory() {
window.history.pushState({ name: "Lee" }, "----", "home.html");
}

页面可编辑

document.designMode = 'on'


举报
0 条评论