/*
* 知识点1: 变量声明提升,但是赋值不不会提升
*/
var a = 1;
if(true) {
console.log(a); // 1
var a = 2;
var b = 3;
}
console.log(a); //2
console.log(b); // 3
b = 4;
/*
* 知识点2: 同一标识符的前提下, 声明都会提升,且函数声明会覆盖变量声明。 但是初始化或赋值时,变量优先级高于函数。
*/
console.log(a) // a(){}
var a = 1;
function a(){};
console.log(a) // 1
/*
* 知识点3: 函数的实参可以通过arguments对应索引来改变值, 函数外变量于函数形参同名时,不会影响形参内的赋值及原始值
*/
var a = 1;
function fun(a, b) {
a = 2;
arguments[0] = 3; // a=3
arguments[1] = 1; // b =1
return a + b; // 4
}
console.log(fun(0, 0)); // 4
console.log(a) // 1
/*
知识点4: for 循环为同步任务,setTimeout 为异步任务。主任务知晓完成后才会将异步任务队列推入执行;
for 循环完成后i 值为5, 所以最后的console.log 输出5
*/
for(var i=0; i<5; i++) {
setTimeout(function(){
console.log("for i:", i) // 输出5个: for i: 5
}, 0)
}
console.log(i) //5
/*
知识点5: 普通函数的继承及实例化为先实例化子类构造函数,后实例父类构造函数;
函数内及原型上的变量,只能在实例化后可访问,直接通过方法访问报 error
(先查找自己 构造函数,然后查找继承对象的构造函数,然后查找继承对象的原型链.... 如果找到则停止后续查找)
*/
function A() {
this.num1 = 1;
};
A.prototype.num2 = 2;
function B(){
this.num1 = 3
};
B.prototype = new A();
var b1 = new B();
console.log(b1.num1); // 3
console.log(b1.num2); // 2
var b2 = B();
console.log(b2.num1); // error
console.log(b2.num2); // error
/*
* 根据数组目录树集合,输出树对象
*/
var data=[
{id: 1, parentId: 0, name:'父节点1'},
{id: 2, parentId: 1, name:'父节点1'},
{id: 3, parentId: 1, name:'子节点11-1'},
{id: 4, parentId: 2, name:'子节点12-1'},
{id: 5, parentId: 3, name:'子节点11-2'},
];
var parentIds = new Set(data.map(item=>item.id)) ; // 自己写一个获取id集合的去重函数。 [0,1,2,3,4]
function createTreeList (arry, newArry, parentId) {
var tempAry = [];
arry.forEach(function(item){
if(item.parentId == parentId) {
tempAry.push(item)
}
});
if(!newArry.length) {
newArry = tempAry;
} else {
newArry.forEach(function(item){
if(item.children) {
createTreeList(arry, item.children, item.parentId);
}
if(item.id == parentId) {
item["children"] = tempAry
}
})
}
if(parentIds.length==0){
return ;
}
createTreeList(arry, newArry, parentIds.splice(0,1)[0])
return newArry;
}
var newArray = createTreeList(data, [], parentIds.splice(0,1)[0]);
console.log('newTree:',newArray)
js基础手写Demo知识点总结
最新推荐文章于 2021-12-26 14:03:50 发布