本文介绍了将多个元素推送到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个元素作为一个数组推送,但却出现错误

I'm trying to push multiple elements as one array, but getting error

> a = []
[]
> a.push.apply(null, [1,2])
TypeError: Array.prototype.push called on null or undefined

我正在尝试做类似我在ruby中做的事情,我当时认为 apply 类似 *

I'm trying to do similar stuff that I'd do in ruby, I was thinking that apply is something like *.

>> a = []
=> []
>> a.push(*[1,2])
=> [1, 2]


推荐答案

使用对象的大部分功能时使用 apply 调用 context 参数必须是您正在处理的对象。

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

在这种情况下,您需要 a.push.apply(a,[1,2])(或更正确 Array.prototype.push.apply(a,[1,2])

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

这篇关于将多个元素推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:38
查看更多