一些js编程题

1、promise 异步同步的区别

console.log('begin');
setTimeout(()=>{
	console.log('setTimeout 1')
	Promise.resolve().then(()=>{
		console.log('promise 1');
		setTimeout(()=>{
			console.log('setTimeout2 and promise1&2');
		})
	}).then(()=>{
		console.log('promise 2')
	}).then(()=>{
		console.log('promise 3 ')
	})
},0)
console.log(end);

执行结果:

 setTimeout 1
 promise 1
 promise 2
 promise 3 
 setTimeout2 and promise1&2

2、输出结果:

if([]==false){console.log(1)}
if({}==false){console.log(2)}
if(([])){console.log(3)}
if([1]==1){console.log(4)}
1
3
4

3、arguments类数组转换为数组的方法:

function fun(){
	console.log(arguments);
	}
	console.log(fun(1,2,3,4,5)); //Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]

arguments其实是一个对象,它与数组一样有索引以及length的属性。但是却不能使用数组的方法api。
但是在实际开发中,我们使用arguments可以很方便的获取到所有的实参,并且也需要对其使用是写数组的方法。

方法一:

function fun(){
   var arr =[];
    console.log(arguments); //Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    for(var i = 0 ; i<arguments.length;i++){
        arr.push(arguments[i]);
    }
    return arr;
}
console.log(fun(1,2,3,4,5)); //(5) [1, 2, 3, 4, 5]

方法二:

function fun(){
    console.log(arguments); //Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    return [].slice.call(arguments);
}
console.log(fun(1,2,3,4,5));  //(5) [1, 2, 3, 4, 5]

当arr.slice() 里面没有实参的时候它返回的其实是数组本身。
而call()在这里就是让arguments对象(本来是没有slice()这一方法的)但是借用了array对象的这个方法 的一种手段。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值