The trap of using splice in Action Script 3.0

Source: Internet
Author: User

If the array contains the same continuous content, such as the following array:
VaR testary: array = [6, 1, 1, 5];

If you want to remove 1, the content of the array will be changed to [6, 5]. But what about the result? Try the following:Code:
For (var I: Int = 0; I <testary. length; I ++ ){
If (testary [I] = 1 ){
Testary. splice (I, 1 );
}
}
Trace (testary );

Output: 6, 1, 5

Why is there another 1? When the splice () method deletes the elements in the logarithm group, when it is cut to the array subscript I = 1, the length of the array is reduced by 1, the position of the next cycle to the lower mark is I = 3, and the element with subscript I = 2 is skipped.

 

The following methods can solve the security problem of using Splice:

1. after each array element is deleted, the subscript is automatically subtracted
Public Function dosplice1 (ary: array): Array {
for (var I: Int = 0; I If (ary [I] = 1) {
ary. splice (I, 1);
I --;
}< BR >}< br> return ary;
}< br> 2. reverse cyclic deletion
Public Function dosplice2 (ary: array): Array {
for (var I: Int = ary. length; I> = 0; I --) {
If (ary [I] = 1) {
ary. splice (I, 1);
}< BR >}< br> return ary;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.