js array method finishing 06

Array.prototype.concat() [ES3]

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

grammar:

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

Examples:

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, in the current array, copies the member at the specified position to another position (will overwrite the original member), and then returns to the current array. That is to say, using this method will modify the current array. target (required): from Start to replace data at this position. start (optional): start reading data from this position, the default is 0. If it is a negative value, it means a reciprocal. end (optional): stop reading data before reaching this position, the default is equal to the array Length. If it is a negative value, it means the reciprocal.)

(The copyWithin() method is a shallow copy of the array, and the size of the array has not changed.)

grammar:

arr.copyWithin(target)

arr.copyWithin(target,start)

arr.copyWithin(target,start,end)

Examples:

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

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

Array.prototype.entries() [ES6]

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

grammar:

a.entries()

Examples:

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 judgment of the array: apply the specified function to the array element to judge, and return true or false)

grammar:

arr.every(callback[,thisArg])

Examples:

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; } ) //true 所有值<10

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

grammar:

arr.fill(value)

arr.fill(value,start = 0)

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

(value 值是必须的;start 开始位置 ,可选、默认值为;end结束位置,可选、默认值为数组的length)

Examples:

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]


(The filter() method returns a subset of the array <also an array, new array>, the passed function is used for logical judgment)

grammar:

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

(element: the current element being processed in the array. index: the index of the current element being processed in the array. array: the current array. thisArg: this point in the fn function.)

Examples:

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]

(The find() method returns the value of the first element of the array that meets the specified function. Otherwise, it returns undefinded)

grammar:

arr.find(callback[,thisArg])

(element: the current element being processed in the array. index: the index of the current element being processed in the array. array: the current array. thisArg: this point in the fn function.)

Examples:

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]

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

grammar:

arr.findIndex(callback[,thisArg])

(element: the current element being processed in the array. index: the index of the current element being processed in the array. array: the current array. thisArg: this point in the fn function.)

Examples:

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]

(The foreach() method is used to traverse each element in the array)

grammar:

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

(CurrentValue: the value of the current element being processed in the array. index: the index of the current element being processed in the array. array: the current array. thisArg: use this value when the callback is executed (ie referenceobject))

Examples:

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

a.forEach(function(element){  

      console.log(element);

});

//a// b// c
(其实数组的遍历有很多方法   for...of..  、for...in.. 等都可以)
Array.prototype.includes() [ES7]

## 在这里插入代码片

(Includes() determines that the array contains a certain element, and returns true or false as appropriate.)

grammar:

arr.includes(searchElement)

arr.includes(searchElement,fromIndex)

(searchElement:搜索的元素,fromIndex:开始搜索元素的索引,从该位置开始搜索)

Examples:

[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 returns -1 if not found, searches from beginning to end)

grammar:

arr.indexOf(searchElement[,fromIndex])

(searchElement:搜索的元素,fromIndex:开始搜索元素的索引,从该位置开始搜索)

Examples:

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]

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

grammar:

arr.lastIndexOf(searchElement)

arr.lastIndexOf(searchElement,fromIndex)

Examples:

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]

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

grammar:

arr.join()

arr.join(separator)

(separator: the concatenation of the connection string)

Examples:

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]

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

grammar:

arr.keys()

Examples:

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 called array to the specified function, and returns an array, which contains the return value of the function, in fact, it is also a traversal of the array)

grammar:

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

(CurrentValue: the value of the current element being processed in the array. index: the index of the current element being processed in the array. array: the current array. thisArg: use this value when executing the callback<optional>)

Examples:

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]

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

grammar:

arr.pop()

Examples:

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

var popped = myFish.pop();

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

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

Array.prototype.push() [ES3]

(The push() method allows the array to be used as a stack. Its function is to add elements to the end of the array and return the changed length of the array)

grammar:

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

(ElementN: add to the end of the array to the element)

Examples:

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]

(The reduce() method uses the specified function to combine the array elements to generate a single value)

grammar:

arr.reduce(callback, [initialValue])

(Callback: callback function, initialValue: initialization value <optional>)

Examples:

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]
//  flattened中的匿名函数执行步骤:

//         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 of combining elements in the reduceRight() method is from right to left, generating a single value)

grammar:

arr.reduceRight(callback[, initialValue])

Examples:

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]

(The reverse() method reverses the order of the elements in the array, and returns the reversed array, which is rearranged on the basis of the original array)

grammar:

a.reverse()

Examples:

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]

(The function of the shift() method is to delete the first element of the array and return it, and then move all the following elements forward by one position to fill the gap. If the array is empty, return undefinded);

grammar:

arr.shift()

Examples:

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 role of the unshift() method is to add elements to the beginning of the array and return the length of the new array)

grammar:

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

Examples:

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 slice or sub-array of the specified array, and its two parameters specify the start and end positions of the slice respectively. The returned array contains all the array elements between the position specified by the first parameter and all the array elements up to but not including the position specified by the second parameter.

grammar:

arr.slice()

arr.slice(begin)

arr.slice(begin, end)

Examples:

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]

The some() method is the logical judgment of the array, he applies the specified function to the array element to judge, and returns true and false. some() is like the "existence" quantifier in mathematics, it returns true when at least one element in the array satisfies the calling decision function.

grammar:

arr.some(callback[, thisArg])

Examples:

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 string unicode encoding). If there is an undefined element, it will be sorted to the end.

grammar:


arr.some(callback[, thisArg])


实例:

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;
})
// 按照升序进行排序
console.log(num) // [1, 2, 3, 8, 10, 21, 29]

Array.prototype.splice() [ES3]

The splice() method 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 elements are removed, an empty array is returned.

grammar:

array.splice(start)

array.splice(start, deleteCount)

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

start
delectCount
item1…

Examples:

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 the elements of the array into strings, and uses localized separators to concatenate these strings to generate the final string.

grammar:

arr.toLocaleString();

arr.toLocaleString(locales);

arr.toLocaleString(locales, options);

Examples:

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]

grammar:

arr.toSource()

Examples:

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

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

*** Many browser manufacturers have not implemented it now

Array.prototype.toString() [ES3]

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

grammar:

arr.toString()

Examples:

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 for each index.

grammar:

arr.values()

Examples:

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]

The initial values ​​of the @@iterator attribute and the values() attribute are the same function object

grammar:

arrSymbol.iterator

Instance

var arr = ['w', 'y', 'k', 'o', 'p'];
// 您的浏览器必须支持for...of循环
// 以及let —— 将变量作用域限定在 for 循环中
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

** The above is a simple operation of javascript array, the specific is based on MDN

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

Guess you like

Origin blog.csdn.net/qq_45555960/article/details/101469721