Javascript-array objects, arrays

Source: Internet
Author: User

1. Create array mode 1. New keyword
var arr = new Array(1, 2, 3);
Mode 2. Creating an Array object using literals
var arr = [1, 2, 3];
2. Detecting whether an object is an array
  1. instanceof (operator), [] instanceof Array
  2. Array.isarray (), HTML5 method, with compatibility issues
3. Common methods for arrays

Specific Check MDN

// 1 栈操作(先进后出)push()pop()       //取出数组中的最后一项,修改length属性// 2 队列操作(先进先出)push()shift()     //取出数组中的第一个元素,修改length属性unshift()   //在数组最前面插入项,返回数组的长度// 3 排序方法reverse()   //翻转数组sort();     //即使是数组sort也是根据字符,从小到大排序// 带参数的sort是如何实现的?// 4 操作方法concat()    //把参数拼接到当前数组slice()     //从当前数组中截取一个新的数组,不影响原来的数组,参数start从0开始,end从1开始splice()    //删除或替换当前数组的某些项目,参数start, deleteCount, options(要替换的项目)// 5 位置方法indexOf()、lastIndexOf()   //如果没找到返回-1// 6 迭代方法 不会修改原数组(可选)every()、filter()、forEach()、map()、some()// 7 方法将数组的所有元素连接到一个字符串中。join()
4. Implementing the Array.join Method

Input: An array, such as var arr = [1, 2, 3, 4, 5]
Output:1|2|3|4|5

Version 1: string concatenation method
function myJoin(array, seperator) {  seperator = seperator || ‘,‘;  array = array || [];  if (array.length == 0){    return ‘‘;  }  var str = array[0];  for (var i = 1; i < array.length; i++) {    str += seperator + array[i];  }  return str;}var array = [6, 3, 5, 6, 7, 8, 0];console.log(myJoin(array, ‘-‘));console.log(array.join(‘-‘))
5. Implementing the Array.reverse Method

Reverses the order of the elements of a string array
Input:["A", "B", "C", "D"]
output:["D", "C", "B", "a"]

Version 1: element I and length-i-1 element interchange, half of I < array in for loop
    function myReverse(arr) {        // 数组为空即返回空数组        if (!arr || arr.length === 0) {            return [];        }        // 遍历到数组长度的一般即可        for (var i = 0; i < arr.length / 2; i++) {            var tmp = arr[i];            arr[i] = arr[arr.length - i - 1];            arr[arr.length - i -1] = tmp;        }        return arr;    }    var array = [‘a‘, ‘b‘, ‘c‘, ‘d‘];    console.log(array);    console.log(myReverse(array));    console.log(array.reverse());
6. Emptying the array
// 方式1 推荐 arr = [];// 方式2 arr.length = 0;// 方式3arr.splice(0, arr.length);
Case 1. An array of wages [1500, 1200, 2000, 2100, 1800], the deletion of wages over 2000

Mode 1: Use auxiliary arrays, traversal, and if filtering. (Disadvantage: Not in-situ operation)

var array =  [1500,1200,2000,2100,1800];var tmpArray = [];for (var i = 0; i < array.length; i++) {  if(array[i] < 2000) {    tmpArray.push(array[i]);  }}console.log(tmpArray);

Mode 2: Use the filter high-order function (functional programming)

var array =  [1500, 1200, 2000, 2100, 1800];array = array.filter(function (item, index) {  if (item < 2000) {    return true;  }  return false;});console.log(array);
Case 2. ["C", "a", "Z", "a", "X", "a"] find the position where each of a in the array appears

Mode 1. Using the Array.indexof method is also a disadvantage.

var array =  [‘c‘, ‘a‘, ‘z‘, ‘a‘, ‘x‘, ‘a‘];do {  var index = array.indexOf(‘a‘,index + 1);  if (index != -1){    console.log(index);  }} while (index > 0);
Case 3. Remove duplicate elements from an array

Mode 1. Using the K-v container, K saves the elements in the original array, and V saves the number of occurrences of the elements in the original array, regardless of the number of times it is saved in the new array.

 //new array var arr = [' C ', ' A ', ' Z ', ' a ', ' X ', ' a '];            Clear duplicate element function clear (array) {///1. The number of occurrences of an element with a key-value container var tmpdict = [];            var tmpdict = {};                for (var i = 0; i < Array.Length; i++) {var item = Array[i];                if (Tmpdict[item]) {tmpdict[item]++;                } else {Tmpdict[item] = 1; }}//2. Saved in a new array.            Elements with occurrences greater than 1 and equal to 1 in the container are added only once to the new array.            var tmparray = [];                for (var key in tmpdict) {if (tmpdict[key] = = 1) {Tmparray.push (key);                        } else {//If there are no elements of the original array in the new array, add if (tmparray.indexof (key) = =-1) {                    Tmparray.push (key);        }}} return tmparray; }//Test Console.log (Clear (arr));  

Javascript-array object, array

Related Article

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.