2

如何从被推入的数组中删除一个元素push

animals = []

class Cat

cat = new Cat

animals.push cat

现在我可以说类似

animals.pull cat

把猫从阵列中拿走?假设cat变量与被推入的变量相同。我只是想创建一种动态集合..

4

3 回答 3

5
index = animals.indexOf cat
animals.splice index, 1 if index isnt -1

Remember, a CoffeeScript array is just a JavaScript array, so you can look at any appropriate documentation.

于 2012-06-12T19:51:57.137 回答
4

如果您push将元素添加到数组中,则会将其添加到最后一个位置。然后您可以将pop其返回。如果您想用数组对堆栈建模,这两种方法很有用。

array = []

array.push 'hello' # array is now ['hello']
array.push 'world' # array is now ['hello', 'world']

alert array.pop() # alerts 'world', array is now ['hello']
alert array.pop() # alerts 'hello', array is now []
于 2012-06-12T20:28:02.343 回答
1

你可以这样做:

animals = []

class Cat

cat = new Cat

animals.push cat

anotherReferenceToCat = animals.pop()

# animals.length === 0
于 2012-06-12T22:39:59.917 回答