我有一个由n个元素组成的数组.数字n是未知的.
I have an array consisting of n elements. The number n is not known. How to delete those n elements from the array?
推荐答案从您的问题来看,您似乎需要从数组中删除所有元素.如果是这样,请将您的数组变量分配给一个新的空数组.我不确定这个简单的解决方案是否是您真正想要的.您需要更准确地回答问题. 如果您想要删除任何随机元素的能力,则数组还不够好.相反,您需要使用Vector,List,LinkedList或ArrayList并使用它们的remove方法. 请参阅 docs.oracle/javase/1.4. 2/docs/api/java/util/Collection.html [ ^ ];其他收集类型在此页面的另请参见"下列出;请点击每个链接,看看它们有什么用.
尝试一下: splice()方法向数组添加元素和/或从数组中删除元素,然后返回删除的元素. 语法: Try this : The splice() method adds and/or removes elements to/from an array, and returns the removed element(s). Syntax: array.splice(index,howmany,element1,.....,elementX)
index :必需.一个整数,指定要在什么位置添加/删除元素 howmany :必需.要删除的元素数.如果设置为0,则不会删除任何元素 element1,...,elementX :可选.要添加到数组中的新元素 Example1:
index : Required. An integer that specifies at what position to add/remove elements howmany : Required. The number of elements to be removed. If set to 0, no elements will be removed element1, ..., elementX : Optional. The new element(s) to be added to the array Example1 :
var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write("Added: " + fruits.splice(2,0,"Lemon") + "<br />"); document.write(fruits);Example2:
Example2 :
var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write("Removed: " + fruits.splice(2,1,"Lemon") + "<br />"); document.write(fruits);输出1:
Output1 :
Added: Banana,Orange,Lemon,Apple,MangoOutput2: 从位置2删除一个元素,然后向数组中的位置2添加一个新元素:
Output2 : Remove one element from position 2, and add a new element to position 2 in the array:
Removed: Apple Banana,Orange,Lemon,Mango
您在看第n个元素吗?然后您可以执行以下操作 Are you looking at the n''th element? Then you can do as below ArrayList a = new ArrayList(); a.Count
更多推荐
删除数组中的元素
发布评论