美文网首页
Javascript数据类型 - Array(上)

Javascript数据类型 - Array(上)

作者: threetowns | 来源:发表于2017-12-31 16:12 被阅读0次
    ja-array-operation

    一、 声明数组

    There are two ways to declare an Array in javascript:

    • Using Array literals — it is just a pair of square brackets followed by zero or more value items separated by commas like —
    var foo = [];
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    • Using Array constructor — it is just creating an array using new keyword like —
    var foo = new Array();
    var days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    

    二、属性(Properties)

    length — the length property of an array is the largest positive integer key plus one.

    三、方法(Methods)

    There are many methods associated with arrays in javascript, some methods modify the existing array(Mutator Methods), some are used to access values or return some required representation and do not change the existing array(Accessor Methods), some for looping over array items(Iterator Methods) and so on. Lets explore few of most commonly used these methods and categories on the bases of there nature.

    1. Mutator Methods

    • Array.prototype.push()  —  push adds one or more elements to the end of an array and returns the updated length of array.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.push('Saturday');  //7
    console.log(days);      // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    
    • Array.prototype.pop() — pop method removes the last element from an array and returns that removed element.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.pop(); //Friday
    console.log(days); //["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]
    
    • Array.prototype.shift() — similar to pop method, shift removes the first element from an array and returns that element.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.shift();      // Sunday
    console.log(days); // [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    
    • Array.prototype.unshift()  —  similar to push method, unshift method add one or more elements to the front of an array and returns the updated length of the array.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.unshift('Saturday'); // 7
    console.log(days);        // [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    
    • Array.prototype.sort() — this method sorts the elements of an array and returns the new sorted array.
    var numbers = [3,45,5,7,32,56,87,11];
    numbers.sort(); //[11, 3, 32, 45, 5, 56, 7, 87]
    console.log(numbers);  //[11, 3, 32, 45, 5, 56, 7, 87]
    
    • Array.prototype.reverse()— this method reverses the order of the elements of an existing array i.e. the first element of array becomes the last, and the last element becomes the first element.
    var numbers = [3,45,5,7,32,56,87,11];
    numbers.reverse(); //[11, 87, 56, 32, 7, 5, 45, 3]
    
    • Array.prototype.splice() — this method modify the existing array by adding new elements or removing elements from the array. Splice method can take any number of arguments, first is the start index and it is required, second is the delete count i.e. the number of element to delete from the start index, if given 0 then nothing is going to delete, it is optional and rest of the arguments are the elements to be added at given index.
    // Syntax - 
    // array.splice(start, deleteCount, item1, item2, ...)
    
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.splice(2,1);   // ["Tuesday"]
    console.log(days);  // ["Sunday", "Monday", "Wednesday", "Thursday", "Friday"]
    days.splice(2,0,'Tuesday');
    console.log(days)   // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    

    2. Accessor Methods —

    • Array.prototype.slice() — slice method can takes two arguments, first is start index and second is end index and returns an array that has only the elements between those two indexes. The start index is required, the end index optional, if end index is not given then extract till end of the array.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.slice(2,4); //["Tuesday", "Wednesday"]
    days.slice(3); //["Wednesday", "Thursday", "Friday"]
    
    • Array.prototype.concat() — this method is used to concatenate or glue arrays together and returns a new array concatenated array.
    var week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    var weekend_days = ['Saturday', 'Sunday'];
    week_days.concat(weekend_days); //["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    
    • Array.prototype.join()— this method flattened all the elements of the array to a single string. The argument passed to join is glued between array elements while joining to string.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.join('-'); //Sunday-Monday-Tuesday-Wednesday-Thursday-Friday
    
    • Array.prototype.includes() — return true or false whether an array contains a certain element, which is passed as an argument in the includes function.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.includes('Sunday'); //true
    days.includes('sunday'); //false
    
    • Array.prototype.indexOf()— Returns the index of first (least) occurrence of element within the array which is given, or -1 if none is found. It also take second argument which is optional and specify from where to start.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.indexOf('Tuesday');    // 2
    days.indexOf('Tuesday', 4); // -1
    days.indexOf('March');      // -1
    
    • Array.prototype.lastIndexOf()— Returns the index of last (greatest) occurrence of element within the array which is given, or -1 if none is found. It also take second argument which is optional and specify from where to start.
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    days.lastIndexOf('Tuesday');    // 2
    days.lastIndexOf('Tuesday', 4); // 2
    days.lastIndexOf('March');      // -1
    

    3.Iteration methods —

    • Array.prototype.filter() — It iterate over the every element of the given array and return a new array having only those element which the provided filtering function returns true.
    var random_numbers = [2,4,5,6,7,9,34,26,45,39];
    random_numbers.filter(function(element){
    return element % 2;
    });
    //[5, 7, 9, 45, 39]
    
    • Array.prototype.find() — similar to filter method, it also iterate over array and return only the first element of array which return true with the provided conditions or functionality.
    var random_numbers = [2,4,5,6,7,9,34,26,45,39];
    random_numbers.find(function(element){
     return element > 20;
    });
    //34
    
    • Array.prototype.forEach() —It iterate and calls a function for each element in the array. This callback function can be called with three parameters, first is element of array, second is index of that element and third is the array being traversed.
    var random_numbers = [1,2,4,5,6,7];
    function logArrayElements(element, index, array) {
      console.log('a[' + index + '] = ' + element);
    }
    random_numbers.forEach(logArrayElements);
    //a[0] = 11
    //a[1] = 21
    //a[2] = 41
    //a[3] = 51
    //a[4] = 61
    //a[5] = 71
    
    • Array.prototype.map() — Creates a new array with the results of calling a provided function on every element in this array.
    var random_numbers = [1,2,4,5,6,7];
    var doubledArray = random_numbers.map(function(element){
      return element * 2;
    });
    console.log(doubledArray); //[2, 4, 8, 10, 12, 14]
    
    • Array.prototype.reduce() — It traverses the array (from left-to-right) and invokes a callback function on each element. The value returned is the progressively passed from callback to callback, and at the end reduce() returns the cumulative value.
    // Syntax - 
    // array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
    
    var rockets = [
         {country:'Russia', launches:32 }, { country:'US', launches:23 },  { country:'China', launches:16 }, 
         { country:'Europe(ESA)', launches:7 }, { country:'India', launches:4 }, { country:'Japan', launches:3 } 
    ];  
    var sum = rockets.reduce(function(total, elem) {   return total + elem.launches; }, 0);    
    sum // 85
    
    • Array.prototype.every()

    • Array.prototype.some()

    4.

    toString()
    valueOf()

    总结

    Array In ES5

    参考

    相关文章

      网友评论

          本文标题:Javascript数据类型 - Array(上)

          本文链接:https://www.haomeiwen.com/subject/vugigxtx.html