js array method collation 06

Posted by KevMull on Thu, 26 Sep 2019 14:39:00 +0200

Array.prototype.concat() [ES3]

(concat() method combines two or more arrays. This method does not change the existing array, but returns the new array.

Syntax:

var new_array = old_array.concat(value1[,value2[, ...[,valueN]]])

Example:

var arr1=['a','b','c'];

var arr2=['d','e','f'];

var arr3=arr1.concat(arr2);

// arr3 is a new array [ "a", "b", "c", "d", "e", "f" ]

Array.prototype.copyWithin() [ES6]

(The copyWithin method, within the current array, copies the members of the specified location to other locations (which overrides the original members), and then returns the current array. That is to say, using this method, the current array will be modified. target (required): Replace data from that location. start (optional): Read data from this location by default of 0. If it is negative, it means reciprocal. end (optional): Stop reading data before reaching this location, which is equal to the array length by default. If it is negative, it means reciprocal.

(The copyWithin() method is the shallow copy of the array, and the size of the array remains unchanged.)

Syntax:

arr.copyWithin(target)

arr.copyWithin(target,start)

arr.copyWithin(target,start,end)

Example:

['alpha','bravo','charlie','delta'].copyWithin(2,0);

// results in ["alpha", "bravo", "alpha", "bravo"]

Array.prototype.entries() [ES6]

(entries() method returns an iterator object of a new array containing key/value pairs for each index in the array. )

Syntax:

a.entries()

Example:

var a = ['a','b','c'];

var iterator = a.entries();

console.log(iterator.next().value);  // [0, 'a']

console.log(iterator.next().value);  // [1, 'b']

console.log(iterator.next().value);  // [2, 'c']



var a = ['a','b','c'];

var iterator = a.entries();

for(lete of iterator){

    console.log(e);

}// [0, 'a']// [1, 'b']// [2, 'c']

Array.prototype.every() [ES5]

(every method is the logical judgement of arrays: Apply the specified judgement to the array elements and return true or false)

Syntax:

arr.every(callback[,thisArg])

Example:

functionisBigEnough(element,index,array){

       return element >= 10;

}

[12,5,8,130,44].every(isBigEnough);// false

[12,54,18,130,44].every(isBigEnough);// true

[1,2,3,4,5,6,7,8].every(function(x){ x < 10; } ) //All true values < 10

Array.prototype.fill() [ES6]
(fill() method fills in all elements of the array from the beginning to the end of the index and the static value)

Syntax:

arr.fill(value)

arr.fill(value,start = 0)

arr.fill(value,start = 0,end = this.length)

(value Value is necessary; start Start position, optional, default value; end End position, optional, default value of array length)

Example:

varnumbers=[1,2,3]

numbers.fill(1);



[1,2,3].fill(4);// [4, 4, 4]

[1,2,3].fill(4,1);// [1, 4, 4]

[1,2,3].fill(4,1,2);// [1, 4, 3]

[1,2,3].fill(4,1,1);// [1, 2, 3]

[1,2,3].fill(4,-3,-2);// [4, 2, 3]

[1,2,3].fill(4,NaN,NaN);// [1, 2, 3]

Array(3).fill(4);// [4, 4, 4]

[].fill.call({length:3},4);// {0: 4, 1: 4, 2: 4, length: 3}

Array.prototype.filter() [ES5]

(fi lt er () method returns a subset of the array < also an array, a new array >, and the function passed is used for logical determination)

Syntax:

var newArray = arr.filter(callback[,thisArg])

Element: The current element being processed in the array. index: index of the current element being processed in an array. Array: The current array. This point in this Arg:fn function.

Example:

var words = ["spray","limit","elite","exuberant","destruction","present"];

var longWords = words.filter(function(word){return word.length > 6;})

// Filtered array longWords is ["exuberant", "destruction", "present"]

Array.prototype.find() [ES6]

(find() method returns the value of the first element of an array of functions that conform to the specified function. Otherwise return undefined)

Syntax:

arr.find(callback[,thisArg])

Element: The current element being processed in the array. index: index of the current element being processed in an array. Array: The current array. This point in this Arg:fn function.

Example:

function isBigEnough(element){

    return element>=15;

}

[12,5,8,130,44].find(isBigEnough);  // 130



function isPrime(element,index,array){
   var start=2;

    while(start<=Math.sqrt(element)){

        if(element%start++<1){

             returnfalse;

        }

    }

     return element>1;

}

console.log([4,6,8,12].find(isPrime));  // undefined, not found

console.log([4,5,8,12].find(isPrime));  // 5

Array.prototype.findIndex() [ES6]

(findIndex() method is very similar to find(), and the return value of findIndex(0) is the index of the array, returning the index of the first element of the array that meets the criteria. Otherwise return - 1)

Syntax:

arr.findIndex(callback[,thisArg])

Element: The current element being processed in the array. index: index of the current element being processed in an array. Array: The current array. This point in this Arg:fn function.

Example:

function isBigEnough(element){

    return element >= 15;

}

[12,5,8,130,44].findIndex(isBigEnough);

// index of 4th element in the Array is returned,

// so this will result in '3'



functionis Prime(element,index,array){

      var start = 2;

      while(start <= Math.sqrt(element)) {

            if(element%start++<1){

                   return false;

             }

       }

        return element>1;

 }

console.log([4,6,8,12].findIndex(isPrime));   // -1, not found

console.log([4,6,7,12].findIndex(isPrime));   // 2

Array.prototype.forEach() [ES5]

(foreach() method is used to traverse every element in an array)

Syntax:

arr.forEach(functioncallback(currentValue, index, array) {
//your iterator
}[,thisArg]);

CurrtValue: The value of the current element being processed in the array. index: index of the current element being processed in an array. Array: The current array. thisArg: When the callback executes, use this value (that is, reference object)

Example:

vara=['a','b','c'];

a.forEach(function(element){  

      console.log(element);

});

//a// b// c
(Actually, there are many ways to traverse arrays.   for...of..  ,for...in.. And so on.)
Array.prototype.includes() [ES7]
## Insert code slices here

(include () determines that the array contains an element and returns true or false as appropriate. )

Syntax:

arr.includes(searchElement)

arr.includes(searchElement,fromIndex)

(searchElement:Search elements, fromIndex: Start searching for the index of the element, and start searching from that location)

Example:

[1,2,3].includes(2);// true

[1,2,3].includes(4);// false

[1,2,3].includes(3,3);// false

[1,2,3].includes(3,-1);// true

[1,2,NaN].includes(NaN);// true

Array.prototype.indexOf() [ES5]

(The indexOf() method searches the entire array for elements with a given value, returns the index of the first element found, or - 1 if not, searches from beginning to end)

Syntax:

arr.indexOf(searchElement[,fromIndex])

(searchElement:Search elements, fromIndex: Start searching for the index of the element, and start searching from that location)

Example:

var array=[2,9,9];

array.indexOf(2);// 0

array.indexOf(7);// -1

array.indexOf(9,2);// 2

array.indexOf(2,-1);// -1

array.indexOf(2,-3);// 0

Array.prototype.lastIndexOf() [ES5]

(lastIndexOf() method is similar to indexOf(), but lastIndexOf() search starts from the end)

Syntax:

arr.lastIndexOf(searchElement)

arr.lastIndexOf(searchElement,fromIndex)

Example:

var numbers=[2,5,9,2];

numbers.lastIndexOf(2);// 3

numbers.lastIndexOf(7);// -1

numbers.lastIndexOf(2,3);// 3

numbers.lastIndexOf(2,2);// 0

numbers.lastIndexOf(2,-2);// 0

numbers.lastIndexOf(2,-1);// 3

Array.prototype.join() [ES3]

(join() method converts all the elements in the array into strings and connects them together, returning the last generated string. The default connector between the connecting elements is',').

Syntax:

arr.join()

arr.join(separator)

(separator: a connector that connects strings)

Example:

var a=['Wind','Rain','Fire'];

a.join();// 'Wind,Rain,Fire'

a.join(', ');// 'Wind, Rain, Fire'

a.join(' + ');// 'Wind + Rain + Fire'a.join('');// 'WindRainFire'

Array.prototype.keys() [ES6]

(keys() method returns an iterator of a new array containing each index key in the array)

Syntax:

arr.keys()

Example:

var arr = ['a',,'c'];

var sparseKeys=Object.keys(arr);

var denseKeys=[...arr.keys()];

console.log(sparseKeys);// ['0', '2']

console.log(denseKeys);// [0, 1, 2]

Array.prototype.map() [ES5]

The (map() method passes each element of the invoked array to the specified function and returns an array containing the return value of the function, which is actually a traversal of the array.

Syntax:

var new_array = arr.map(callback[,thisArg])

CurrtValue: The value of the current element being processed in the array. index: index of the current element being processed in an array. Array: The current array. thisArg: Use this value < optional > when performing callbacks

Example:

var kvArray = [ {key:1,value:10},

                {key:2,value:20},

                {key:3,value:30} ];

var reformattedArray = kvArray.map(
    function(obj) {

        var rObj = {};

        rObj[obj.key] = obj.value;

        returnr Obj;

      }

);

console.log(reformattedArray);  // [{1: 10}, {2: 20}, {3: 30}],

Array.prototype.pop() [ES3]

(pop() method allows the array to be used as a stack. Its purpose is to delete the last element of the array, reduce the length of the array and return the value it deleted, and if the array is empty, return undefined)

Syntax:

arr.pop()

Example:

var myFish = ['angel','clown','mandarin','sturgeon'];

var popped = myFish.pop();

console.log(myFish);  // ['angel', 'clown', 'mandarin' ]

console.log(popped);  // 'sturgeon'

Array.prototype.push() [ES3]

(push() method allows arrays to be used as stacks. Its purpose is to add elements at the end of the array and return the length of the array as it changes.)

Syntax:

arr.push([element1[, ...[,elementN]]])

(elementN: Add to the end of the array to the element)

Example:

var sports=['soccer','baseball'];

var total=sports.push('football','swimming');

console.log(sports);  // ['soccer', 'baseball', 'football', 'swimming']

console.log(total);// 4

Array.prototype.reduce() [ES5]

(reduce() method combines array elements with specified functions to generate a single value)

Syntax:

arr.reduce(callback, [initialValue])

(callback: callback function, initial Value: initialization value < optional >)

Example:

var sum = [0,1,2,3].reduce(function(a,b){

         returna+b;

},0);// sum is 6



var flattened = [[0,1],[2,3],[4,5]].reduce(

        function(a,b){

              return a.concat(b);

       },[]

);

// flattened is [0, 1, 2, 3, 4, 5]
//  The anonymous function in flattened executes steps:

//         a                    b                     retrun

//         []                  [0,1]                  [0,1]

//        [0,1]                [2,3]               [0,1,2,3]

//      [0,1,2,3]              [4,5]           [0,1,2,3,4,5]

Array.prototype.reduceRight() [ES5]

(The reduceRight() method is similar to the reduce() method, except that the order in which the reduceRight() method combines elements is from right to left, generating a single value)

Syntax:

arr.reduceRight(callback[, initialValue])

Example:

var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
    return a.concat(b);
}, []);

// flattened is [4, 5, 2, 3, 0, 1]

Array.prototype.reverse() [ES3]

(reverse() method reverses the elements in the array and returns the inverse array, which is rearranged on the basis of the original array.

Syntax:

a.reverse()

Example:

var a=['one','two','three'];

var reversed=a.reverse();

console.log(a);// ['three', 'two', 'one']

console.log(reversed);// ['three', 'two', 'one']

Array.prototype.shift() [ES3]

(shift() method deletes the first element of the array and returns it, then moves all the elements that follow to a position to fill the vacancy, and returns undefined if the array is empty;

Syntax:

arr.shift()

Example:

var myFish=['angel','clown','mandarin','surgeon'];

console.log('myFish before:',myFish);

// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']

var shifted=myFish.shift();

console.log('myFish after:',myFish);

// myFish after: ['clown', 'mandarin', 'surgeon']

Array.prototype.unshift() [ES3]

(The unshift() method adds elements at the beginning of the array to return the length of the new array)

Syntax:

arr.unshift([element1[, ...[,elementN]]])

Example:

var arr=[1,2];

arr.unshift(0);// result of call is 3, the new array length

// arr is [0, 1, 2]

arr.unshift(-2,-1);// = 5

// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);// arr is [[-3], -2, -1, 0, 1, 2]
(shift() )

Array.prototype.slice() [ES3]

The slice() method returns a fragment or subarray of the specified array, with two parameters specifying the start and end positions of the fragment, respectively. The returned array contains all array elements between the location specified by the first parameter and all positions specified by the second parameter, but not by the second parameter.

Syntax:

arr.slice()

arr.slice(begin)

arr.slice(begin, end)

Example:

var a = ['zero', 'one', 'two', 'three'];
var sliced = a.slice(1, 3);

console.log(a);      // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['one', 'two']

Array.prototype.some() [ES5]

some() method is the logical judgement of an array. It uses the specified function to determine the elements of an array and returns true and false. some() returns true when at least one element in the array satisfies the calling decision function, just like the quantifier of existence in mathematics.

Syntax:

arr.some(callback[, thisArg])

Example:

function isBiggerThan10(element, index, array) {
   return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

Array.prototype.sort() [ES3]

The sort() method sorts the elements in the array and returns the sorted array. When there are no parameters, the array elements are sorted in alphabetical order (the default sort order is based on the unicode encoding of the string). If there is an undefined element, it will be left to the tail.

Syntax:

arr.some(callback[, thisArg])

//Example:

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
//unicode sort

var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.

var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.


var num = [1, 10, 21, 2, 29, 3, 8];
num.sort((a,b) => {
    return a - b;
})
// Sort in ascending order
console.log(num) // [1, 2, 3, 8, 10, 21, 29]

Array.prototype.splice() [ES3]

splice() is a general method for inserting and deleting elements in an array. If only one element is deleted, an array of elements is returned. If no element is removed, an empty array is returned.

Syntax:

array.splice(start)

array.splice(start, deleteCount)

array.splice(start, deleteCount, item1, item2, ...)

start
delectCount
item1...

Example:

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); // insert 'drum' at 2-index position
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); // remove 1 item at 2-index position (that is, "drum")
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]

Array.prototype.toLocaleString() [ES3]

The toLocaleString() method converts elements of an array into strings, and uses localization separators to connect these strings to produce the final string.

Syntax:

arr.toLocaleString();

arr.toLocaleString(locales);

arr.toLocaleString(locales, options);

Example:

var number = 1337;
var date = new Date();
var myArr = [number, date, 'foo'];

var str = myArr.toLocaleString();

console.log(str);
// logs '1337,6.12.2013 19:37:35,foo'
// if run in a German (de-DE) locale with timezone Europe/Berlin


var prices = ['¥7', 500, 8123, 12];
prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
// "¥7,¥500,¥8,123,¥12"

Array.prototype.toSource() [Non-standard]

Syntax:

arr.toSource()

Example:

var arr = new Array('a', 'b', 'c', 'd');

arr.toSource();
//returns ['a', 'b', 'c']

*** Now many browser vendors have not implemented it.

Array.prototype.toString() [ES3]

The toString() method converts the elements of the array into strings and splits the list of zi-cu strings with commas. (Similar to the join() method of an array without parameters)

Syntax:

arr.toString()

Example:

var months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.toString(); // "Jan,Feb,Mar,Apr"

Array.prototype.values() [ES6]

The values() method returns an iterator object of a new array containing the values in the array of each index.

Syntax:

arr.values()

Example:

var a = ['w', 'y', 'k', 'o', 'p'];
var iterator = a.values();

console.log(iterator.next().value); // w
console.log(iterator.next().value); // y
console.log(iterator.next().value); // k
console.log(iterator.next().value); // o
console.log(iterator.next().value); // p


var arr = ['w', 'y', 'k', 'o', 'p'];
var iterator = arr.values();

for (let letter of iterator) {
  console.log(letter);
}

//  w
//  y
//  k
//  o
//  p

Array.prototype@@iterator [ES6]

@@ both iterator attribute and values() attribute have the same initial value as the function object

Syntax:

arrSymbol.iterator

Example;

var arr = ['w', 'y', 'k', 'o', 'p'];
// Your browser must support for...of loops
// And let -- limit the scope of variables to a for loop
for (let letter of arr) {
  console.log(letter);
}


var arr = ['w', 'y', 'k', 'o', 'p'];
var eArr = arr[Symbol.iterator]();
console.log(eArr.next().value); // w
console.log(eArr.next().value); // y
console.log(eArr.next().value); // k
console.log(eArr.next().value); // o
console.log(eArr.next().value); // p

** These are simple operations for javascript arrays, specifically based on MDN

Reference: https://github.com/freeshineit/javascript-array

Topics: Fragment Attribute Javascript encoding