前端题目整理

听了冰山工作室的每日一题,整理下来

  • 如何跳出forEach循环

every和some方法

a.some(item=>{return item === 2})
a.every(item=>{return item !== 2})
跑空循环

var tag;
a.forEach(item=>{if(!tag){console.log("do something");if(item === 4){tag=true}}})

修改索引
关于foreach里的数组长度:
在foreach里使用push等操作并不会使循环的次数发生变化,如下例:

var a=[1,2];
a.forEach(item=>{a.push(8);console.log(a.length)});
//3
//4

可以看出a的长度发生变化,但是只循环了两次。

a.forEach(item=>{a.unshift(8);console.log(item,a)})
//1  [8, 1, 2]
//1  [8, 8, 1, 2]

下例修改长度来停止循环,但是a也被改变辽

a.forEach(item=>{console.log(item);if(item === 4){a.length=0}})

下面这个推荐

a.forEach(item=>{console.log(item);if(item === 4){a=a.splice(0)}})
  • 延伸:

splice方法详解

arrayObject.splice(index,howmany,item1,.....,itemX)

从index位置开始截取howmany个,把item1到itemx拼接上去,返回被截取的元素,改变arrayObject。

slice方法
详见字符串的包装对象方法
数组和字符串都有的方法有

var a=Object.getOwnPropertyNames(String.prototype);
var b=Object.getOwnPropertyNames(Array.prototype);
a.reduce((init,next)=>{b.includes(next)&&init.push(next);return init;},[])
//["length", "constructor", "concat", "includes", "indexOf", "lastIndexOf", "slice", "toString"]

slice,concat,indexOf,includes

  • 数组扁平化

reduce

function revert(val){
return val.reduce((init,next)=>{
if(next instanceof Array){
init = init.concat(revert(next))
console.log(revert(next))
}else{
init = init.concat(next)
}
return init;
},[])}
revert([1,2,[3,4]])

后来在网上看到另一种简洁写法:

function flatten(arr) {
    return arr.reduce(function(prev, next){
        return prev.concat(Array.isArray(next) ? flatten(next) : next)
    }, [])
}

toString()

[1,2,3,[4,5]].toString().split(',')

es6扩展运算符

var a= [1,2,[3,4]];
while(a.some(item=>Array.isArray(item))){a=[].concat(...a)}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值