Array de--indexof method in JavaScript

Source: Internet
Author: User

In JavaScript, sometimes we use arrays to go heavy. I am here to introduce you I think the simplest practical method of-indexof () to heavy.

1  var  arr = [1,1,1,2,2,2,3,3,4,5,6,2,1 2  var  arr2 = []; 3  for  (var  i = 0;i < Arr.length;i++ 4  
       
        if 
        (Arr2.indexof (arr[i]) = = -1) { 5   Arr2.push (Arr[i])  6
        }  7   }  8  console.log (arr2)//[1,2,3,4,5,6] 

It's a very simple principle, but before you know it, you need to understand the indexOf () method in JavaScript.

In W3cschool It's explained that this is the

The method will retrieve the string stringobject from beginning to end to see if it contains substring searchvalue. The position at which to begin retrieving is at the fromindex of the string or at the beginning of the string

(When Fromindex is not specified). If a searchvalue is found, the position of the first occurrence of the Searchvalue is returned. The character position in Stringobject is starting at 0.

Because of the case-sensitivity problem there is a little demo

var str= "Hello world!" document.write (Str.indexof (//0//-1//6

The IndexOf () method is case-sensitive!

If the string value that you want to retrieve does not appear, the method returns-1.

ARR2 is preferred to index Arr[i] (single string), because arr2 is empty so it can be indexed to the value of arr[i], but the value in arr2 per loop will be more, when indexed to the same value

Will not be added to the arr2, all of which have the effect of the array de-weight.

Array de--indexof method in JavaScript

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.