1. [].slice.call(lis): 将伪数组转换为真数组
<ul id="fragment_test">
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
// lis是伪数组(是一个特别的对象, length和数值下标属性)
const lis = document.getElementsByTagName('li');
console.log(lis instanceof Object, lis instanceof Array,lis.forEach);//true false undefined
// 数组的slice()截取数组中指定部分的元素, 生成一个新的数组
const lis2 = Array.prototype.slice.call(lis); // lis.slice()
console.log(lis2 instanceof Object, lis2 instanceof Array,lis2.forEach);//true true function
2. node.nodeType: 得到节点类型
<div id="test">IT</div>
const elementNode = document.getElementById('test');
const attrNode = elementNode.getAttributeNode('id');
const textNode = elementNode.firstChild;
console.log(elementNode.nodeType, attrNode.nodeType, textNode.nodeType);
3. Object.defineProperty(obj, propertyName, {}): 给对象添加/修改属性(指定描述符)
configurable:true/false 是否可以重新define
enumerable:true/false 是否可以枚举(for…in / keys())
value:指定初始值
writable:true/false value是否可以修改存取(访问)描述符
get:函数,用来得到当前属性值
set:函数,用来监视当前属性值的变化
const obj = {
firstName: 'A',
lastName: 'B'
};
Object.defineProperty(obj, 'fullName', {
//访问描述符
// 当读取对象此属性值时自动调用, 将函数返回的值作为属性值, this为obj
get () {
return this.firstName + "-" + this.lastName
},
// 当修改了对象的当前属性值时自动调用, 监视当前属性值的变化, 修改相关的属性, this为obj
set (value) {
const names = value.split('-');
this.firstName = names[0];
this.lastName = names[1]
}
});
console.log(obj.fullName); // A-B
obj.fullName = 'C-D';
console.log(obj.firstName, obj.lastName); // C D
const obj = {
firstName: 'A',
lastName: 'B'
};
Object.defineProperty(obj, 'fullName2', {
configurable: false, //是否可以重新define
enumerable: true, // 是否可以枚举(for..in / keys())
value: 'A-B', // 指定初始值
writable: false // value是否可以修改
});
console.log(obj.fullName2); // A-B
obj.fullName2 = 'E-F';
console.log(obj.fullName2); // A-B
4. Object.keys(obj): 得到对象自身可枚举的属性名的数组
const obj = {
firstName: 'A',
lastName: 'B'
};
obj.fullName = 'A-B'
const names = Object.keys(obj);
console.log(names);
5. DocumentFragment: 文档碎片(高效批量更新多个节点)
- document: 对应显示的页面,包含n个elment 一旦更新document内部的某个元素界面更新。
- documentFragment:内存中保存n个element的容器对象(不与界面关联),如果更新framgnet中的某个element,界面不变。
<ul id="fragment_test">
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
const ul = document.getElementById('fragment_test');
// 1. 创建fragment
const fragment = document.createDocumentFragment();
// 2. 取出ul中所有子节点取出保存到fragment
let child;
while(child=ul.firstChild) { // 一个节点只能有一个父亲
fragment.appendChild(child) // 先将child从ul中移除, 添加为fragment子节点
}
// 3. 更新fragment中所有li的文本
Array.prototype.slice.call(fragment.childNodes).forEach(node => {
if (node.nodeType===1) { // 元素节点 <li>
node.textContent = 'aaa'
}
});
// 4. 将fragment插入ul
ul.appendChild(fragment)
6. obj.hasOwnProperty(prop): 判断prop是否是obj自身的属性
const obj = {
firstName: 'A',
lastName: 'B'
};
obj.fullName = 'A-B'
console.log(obj.hasOwnProperty('fullName'), obj.hasOwnProperty('toString')); // true false