使用pop()报错,获取除数组最后一项的数据,获取数组最后一项数据,深浅拷贝问题。

使用pop()删除数组报错,data.pop is not a function

const dateRemind = _.get(chartData,'reply.result.dateRemind','');
let notimeOut = dateRemind;
notimeOut.pop();
console.log('notimeOut',notimeOut);

报错:Uncaught TypeError : notimeOut.pop is not a function

分析报错原因:pop只能删除数组,notimeOut是否是数组呢,notimeOut由dateRemind复制,dateRemind的_.get的最后一个是默认值,在上述代码里是'',是一个字符串,当数据没请求到时,dateRemind(notiemOut)是一个'',不是一个数组,所以.pop()报错,应该将默认值改为[].

const dateRemind = _.get(chartData,'reply.result.dateRemind',[]);
let notimeOut = dateRemind;
notimeOut.pop();
console.log('notimeOut',notimeOut);

注意:在报错上方打印。

const dateRemind = _.get(chartData,'reply.result.dateRemind','');
let notimeOut = dateRemind;
console.log('notimeOut',notimeOut); // 在这里打印将会看到notimeOut不是一个数组,而是一个空字符串
notimeOut.pop();
//获取数组的最后一个数据
const timeout = dateRemind.slice(-1);

slice截取数据为什么没报错呢,因为slice可以截取数组,也可以截取字符串。

在上述中,let notimeOut = dateRemind;是为了不改变dateRemind的值,删除数组,原数组dateRemind也改变了,这里出现了深浅拷贝的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值