博客
关于我
JS数组追加数组采用push.apply的坑
阅读量:469 次
发布时间:2019-03-06

本文共 493 字,大约阅读时间需要 1 分钟。

当我在JavaScript中使用a.push.apply(a, b)来将数组b添加到数组a中时,发现当b很大时会抛出RangeError。特别是在一些浏览器下,b的元素数量达到125624时会出问题,而稍微减少一个元素则能通过。这种问题的出现让我感到困惑。

最初,我认为这可能是浏览器处理这种方法时的性能问题,但后来发现问题的根源是调用栈的深度。每次push操作可能会递归调用,处理大量元素时容易导致栈溢出。

通过搜索,我发现其他开发者也遇到了类似的问题。有人建议使用Array.prototype.extend,但现代浏览器中这方法不推荐,因为它可能导致栈溢出。更好的方法是使用for...of或for循环逐个添加元素,避免递归栈溢出。

此外,使用Array.from、slice或concat方法也能高效合并数组,避免栈溢出。这些方法直接且可靠。性能方面,forEach和for...of循环更高效,特别是处理大数据时。

总结:a.push.apply(a, b)在处理大数组时导致栈溢出,应改用更安全的方法如for循环或数组合并方法。选择合适的方法不仅解决问题,还能提升程序性能。

转载地址:http://drcbz.baihongyu.com/

你可能感兴趣的文章
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>