JavaScript基础知识4点(2019.1.3)
2019-01-04 本文已影响13人
小进进不将就
1、如题
(1)以下代码输出什么?
for(var i = 0; i < 10; i++) {
setTimeout(() => {
console.log(i)
}, 0)
}
输出:10个10
(2)如何输出0-9?
① 将 var 改成 let
② 闭包:
for(var i = 0; i < 10; i++) {
(function(i){
setTimeout(() => {
console.log(i)
}, 0)
})(i)
}
2、箭头函数 this 的指向问题
箭头函数的 this 指向是固定不变的,即指向定义函数的环境;
使用 function 定义的函数,this 的指向是随着调用环境的变化而变化的。
function:
function getName() {
console.log(this)
}
let obj={aa:getName}
getName() //Window
obj.aa() //Object
箭头函数:
let getName=()=> {
console.log(this)
}
let obj={aa:getName}
getName() //Window
obj.aa() //Window
3、for...in 和 for...of 的区别
例:
let arr=[ 'a','b','c' ]
(1)使用 for...in 遍历数组
- 输出的 item 是数组的下标的字符串形式
for(let item in arr){
console.log(item) //0 1 2
console.log(typeof item) //string string string
}
- 会遍历原型链上的属性(key)
arr.name='chen'
for(let item in arr){
console.log(item) //'0' '1' '2' 'name'
}
(2)使用 for...of 遍历
- 不会遍历原型链上的属性,返回数组的 value 值
let arr=['a','b','c']
arr.name='chen'
for(let item of arr){
console.log(item) //'a' 'b' 'c'
}
- 可以使用 break、continue、return
for(let item of arr){
if(item==='c') return 1
console.log(item) //'a' 'b'
}
详细的可以参考这篇文章:https://www.jianshu.com/p/c43f418d6bf0
4、flex 布局的 flex-grow 和 flex-shrink 属性有什么用?
- flex-grow
项目的放大比例,默认为 0,即如果存在剩余空间,也不放大。
div{
flex-grow: 1;
}
- flex-shrink
项目的缩小比例,默认为 1,即如果空间不足,项目会缩小。
.box {
flex-shrink: 1;
}
(完)