JavaScript: Array Complete

Keywords: Javascript Attribute less ascii

Origin: http://www.cnblogs.com/leee/p/5509607.html#pop

Stack/Queue

Stack: Bucket.There is only one opening (in and out).FIFO, LIFO
 Queue: People's team.There are two openings.FIFO, LIFO

POP Delete Last Item (Stack)

Deletes the last item and returns the value of the deleted element; returns undefine if the array is empty
var a = [1,2,3,4,5];
a.pop();//a: [1, 2, 3, 4]
a.pop();//a: [1, 2, 3]
a.pop();//a: [1, 2]

shift deletes the first item (queue)

Deletes the first item of the original array and returns the value of the deleted element; returns undefine if the array is empty
var a = [1,2,3,4,5]; 
a.shift(); //a: [2,3,4,5]
a.shift(); //a: [3, 4, 5]

push up to the end (stack)

And returns the new array length;
var a = [1,2,3,4,5]; 
a.push(6);//[1, 2, 3, 4, 5, 6]
aa.push('xx');//[1, 2, 3, 4, 5, 6, "xx"]   Return Length7
a.push('yy');//[1, 2, 3, 4, 5, 6, "xx", "yy"]   Return Length8

unshift up to the top (queue)

And returns the new array length;
var a = [1,2,3,4,5]; 
a.unshift();//[1, 2, 3, 4, 5]
a.unshift("cc");//["cc", 1, 2, 3, 4, 5]  Return Length6
a.unshift("aaa");//["aaa", "cc", 1, 2, 3, 4, 5]  Return Length7

reverse array flip

And returns the flipped array, which is flipped
var a = [1,2,3,4,5]; 
a.reverse()//a: [5, 4, 3, 2, 1] Returns [5, 4, 3, 2, 1]

join array to string

And returns the string, the original array muted
var a = [1,2,3,4,5]; 
var b=a.join('||');//b:"1||2||3||4||5"    a:[1,2,3,4,5]

Slice intercept (slice) array returns `intercepted array', `original array unchanged`

Returns a new array of items from the specified start index (inclusive) to the end index (exclusive) in the original array. , index starts at 0
Return to New Array!!!a unchanged, as if related to value passing reference passing
var a = ['a','b','c','d','e']; 
a.slice(1,3);//["b", "c"]  a:['a','b','c','d','e']
a.slice(0,4);//["a", "b", "c", "d"]
a.slice(3,4);//["d"]
/*Parameter 1*/
a.slice(2);["c", "d", "e"]     //Intercept from the third (inclusive), defaulting to the last.Index is the length of the array itself
a.slice(0);//['a','b','c','d','e']  //New arrays, like old arrays, refer to different values Passing Reference Passing has a relationship
/*Parameter 0*/
a.slice();//And a.slice(0)equivalence   //New arrays, like old arrays, refer to different values Passing Reference Passing has a relationship

/*If there is a negative number in the slice() method's argument, use the length of the array plus the number to determine the corresponding bit
 Set.For example, a call to slice(-2,-1) on an array containing five items and a call to slice(3,4) result in
 The results are the same.If the end position is less than the start position, an empty array is returned.*/
a.slice(3,4);//["d"]  
a.slice(-2,-1);//["d"] This is done from the right, starting with the last element, and the first on the right is0,Negative numbers to the left minus one in turn

splice spliced array returns `spliced element array` ` original array change` can achieve `delete before shift', `delete after pop', `increase before unshift', `increase after push`the same effect

Returns a spliced array of elements, the original array changes, and the index starts at 0
/*Parameter 0*/
var a = ['a','b','c','d','e']; 
a.splice()//Return to [] a:["a", "b", "c", "d", "e"]  Truncate an empty array.The original array is unchanged.
/*Parameter 1*/
var a = ['a','b','c','d','e']; 
a.splice(0);//['a','b','c','d','e']; a:[]//The original array is empty [].Truncate from the first bit, default array length.
var a = ['a','b','c','d','e']; 
a.splice(2);//Return ["c", "d", "e"]    Original Array a:["a", "b"]
/*There are two parameters*/
//The first parameter is the index (from0Start), and the second is length
var a = ['a','b','c','d','e']; 
a.splice(0,2);//["a", "b"]   a:["c", "d", "e"]
a.splice(0,2);//["c", "d"]   a:["e"]

var a = ['a','b','c','d','e']; 
a.splice(0,1);//["a"] a:["b", "c", "d", "e"] with shift Delete before

var a = ['a','b','c','d','e']
a.splice(a.length-1,1)l//["e"]  a:["a", "b", "c", "d"]  with pop Delete before

var arr=[1,3,5,777,'e']  
arr.splice(2,1)  //arr:[1, 3, 777, "e"]  You can delete any element of the array!!

/*Parameter greater than 2*/
//splice(start,deleteCount,val1,val2,...): deleteCount item is deleted from the start position and val1,val2,... 
var a = ['a','b','c','d','e']; 
a.splice(3,1,10,21,238,99);//["d"]    a:["a", "b", "c", 10, 21, 238, 99, "e"]

var a = ['a','b','c','d','e']; 
a.splice(a.length,100000000,88)//Returns [] the element after the last element, intercepts any length, must be empty a:["a", "b", "c", "d", "e", 88]  with push After increase

var a = ['a','b','c','d','e']; 
a.splice(a.length,0,88)//Returns [] the element after the last element, intercepts any length, must be empty a:["a", "b", "c", "d", "e", 88]  with push After increase

var a = ['a','b','c','d','e'];
a.splice(0,0,88,99)//Return [] intercept length from first element0Must be empty   a:[88, 99, "a", "b", "c", "d", "e"]   with unshift Pre-increase

concat number combination Union

Return the merged new array, original array muted
var a = ['a','b','c','d','e']; 
a.concat([88,99]);//["a", "b", "c", "d", "e", 88, 99]   a:["a", "b", "c", "d", "e"]

var b= [9999,10000]
a.concat(b);//  ["a", "b", "c", "d", "e", 9999, 10000]  a:["a", "b", "c", "d", "e"]

sort array sorting nature

//Pit 1: After sorting, it affects itself (instead of generating a new array) 
//Pit 2: By default, the sort method is sorted alphabetically by ascii, not by what we think is numeric size
  var arr5=[100,19,52,502];
  arr5.sort();                 
  console.log(arr5);     //arr5:[100, 19, 502, 52]  

//Usage 3: Change the default comparison number size to sort join function(a,b){return a-b}

//Question 4:a,b stands for.. arguments[0] and arguments[1]//
function compare2Val(a,b){return a-b}
var arr6=[100,19,52,502];
arr6.sort(compare2Val); //The call does not require a pass-through,
 console.log(arr6); //arr6: [19, 52, 100, 502]

//Invoke the nature of not passing parameters
 function compare2Argument(){return arguments[0]-arguments[1]}
 var arr7=[100,19,52,502];
arr7.sort(compare2Argument); //[19, 52, 100, 502]
 console.log(arr7); //arr6: [19, 52, 100, 502]



/*************Total Comparisons Conclusion************/
//Question 5 Total number of comparisons: n(n-1)/2 n is the length of the array

//A: 1: sum of the number of comparisons in each round 
//A: 2: (Array length-1+Array length-2+Array length-3...+1)  

/*
Example array length 6 comparisons: 5+4+3+2+1=15    
Example array length 5 comparisons: 4+3+2+1=10    
Example array length 4 comparisons: 3+2+1=6    

//High school 1+2+3+.... +n=?
Answer:
Set S=1+2+...+(n-1)+n,
S=n+(n-1)+...+2+1
∴2S=(1+n)+[2+(n-1)]+...+[(n-1)+2]+(n+1)
=n(n+1)
∴S= n(n+1)/2,
That is, 1+2+...+(n-1)+n= n(n+1)/2.
*/

//Number of rounds of comparison: Array length-1 Each round of comparison produces a maximum value placed on the rightmost of the array, which does not participate in the next round of comparison
//Number of current round comparisons: Array length - Current number of rounds  
/*************Conclusion**************/

//Number of wheels 4 () - 13
//Round 1: 4-1 3 comparisons [19,100,52,502]; [19,52,100,502]; [19,52,100,502]; 3 Comparisons
//Second round: 4-2 compares 2 discards of 502, ---> [19,52,100,502]; [19,52,100,502]; makes only 2 Comparisons of 19,52,52,100
//Round 3: 4-3 comparisons 1 throw away 100,502--->[19,52,100,502]; only 1 Comparison of 19,52




//5. Common ways to develop  
//Example: Sort by age
function person(name,age){
    this.Name=name;
    this.Age=age
}
var  personArray=[];
personArray.push(new person("LiKe",18));
personArray.push(new person("Tom",58));
personArray.push(new person("Lucy",22));
personArray.push(new person("Haimei",16));

function compareAge(a,b){
    return a.Age-b.Age;
}
personArray.sort(compareAge);
console.log(personArray);//Haimei  LiKe  Lucy Tom  

ES5

Array.isArray(a) determines if a is a true Array

Array.isArray([])  //true
Array.isArray({})  //false
Array.isArray(11)  //false
Array.isArray(null) //false
Array.isArray(undefined) //false

indexOf(element,startIndex) array first element index

And returns the element index, no Return-1 exists, start position defaults from 0.Array.prototype.indexOf(e,i)```Start position I is optional
var arr=[1,5,7,'str','str','str',9,10] 
arr.indexOf('str')//3
arr.indexOf('str',4)//4
arr.indexOf('f');//-1

lastIndexOf(element,endIndex) array last element index

Array.prototype.lastIndexOf(e,i)```Last position I is optional, default arr.length-1
var arr=[1,5,7,'str','str','str',9,10] 
arr.lastIndexOf('str')//5
arr.lastIndexOf('str',4)//4 This is the focus

The following contexts are flexible settings for the execution context of callback functions

Are there elements in some(fn,context) array that meet the ~.

some(fn(value,index,array){return .}, undefined)```undefined is optional and can be undefined, giving you the flexibility to set the execution context of the callback function, Array.prototype.some(fn,context)
var arr=[1,5,7,'str',[99]]
arr.some(function(value,index,array){return Array.isArray(value)})//True //return Meaning of Execution.Array.isArray(value) "Test function" means.As long as the element value satisfies the test (the test returns true), some traversal function returns true  
arr.some(function(value,index,array){return typeof(value)=='string'})//true

every(fn,context) `Does each element in the array meet the ~.condition`

Array.prototype.every(fn,context)
var aa=[[],[1]];
aa.every(function(currentValue,index,array)){return Array.isArray(currentValue)}//true
var bb=['',[]];
bb.every(function(currentValue,index,array){return Array.isArray(currentValue)},undefined)//false

filter(fn,context) returns an array of elements that pass the test FN

Array.prototype.filter(fn,context)
var arr=[1,5,7,'str','str','str',9,10]
arr.filter(function(value,index,array){return typeof(value)=='number'})//[1, 5, 7, 9, 10]

reduce(fn, initialValue) `From left to right, use the function r to aggregate each element of the array.You can optionally set an initial value v`

Array.prototype.reduce(fn,context),prev, cur, index, array note the parameters of the function
Generally speaking, prev starts with the first element in the array and cur is the second element. But when you pass in an initial value, the first prev will be the initial value and cur will be the first element in the array.
//Know beforehand: 15+[6]=156
var values = [1,2,3,4,5,[6]];
var i = 0;
var sum = values.reduce(function (prev, cur, index, array) {
   console.log('Head value:',prev, 'Current Value',cur,'Number of comparisons:',++i,'cur Index of:',index);//prev first cycle, the first value.Values for subsequent loops are calculated logically
   return prev + cur;//The resulting header value, which participates in the next cycle, is assigned to the prev.Of course, the next loop header value will also do this logic with the next current value (plus here)
});
console.log(sum);
/* Result
 Header value: 1 Current value 2 Comparisons: Index of 1 cur: 1
 Head value: 3 Current value 3 Compare times: Index of 2 cur: 2
 Head value: 6 Current value 4 Comparisons: Index of 3 cur: 3
 Head value: 10 Current value 5 Comparisons: 4 cur Index: 4
 Head value: 15 Current value [6] Compare times: Index of 5 cur: 5
156
*/

/*Second example, refer to Zhang Xinxu's example*/
var matrix = [
  [1, 2],
  [3, 4],
  [5, 6]
];
// Flattening of two-dimensional arrays
var flatten = matrix.reduce(function (previous, current) {
  console.log(previous);//2nd cycle length-1
  return previous.concat(current);
});
console.log(flatten);//[1, 2, 3, 4, 5, 6]
/*
[1, 2]
[1, 2, 3, 4]
*/
/*The third example uses the off method of es6, which converts the class array, the class array variable, into an array.Similar to new Array*/
var matrix = [
  999,
  [3, 4],
  [5, 6]
];
// Flattening of two-dimensional arrays
var flatten = matrix.reduce(function (previous, current) {
    if (!Array.isArray(previous)) {
        previous = Array.of(previous);
    }
    return previous.concat(current);
});
console.log(flatten);//[999, 3, 4, 5, 6]
/*Fourth example, two parameter references: http://www.jb51.net/article/60502.htm*/
var arr = ["apple","orange"];
 
function noPassValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
     
    return prev + " " +next;
  });
}
function passValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
     
    prev[next] = 1;
    return prev;
  },{});
}
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());

/* 
prev: apple
next: orange
No Additional parameter: apple orange
----------------
prev: Object {}
next: apple
prev: Object {apple: 1}
next: orange
With {} as an additional parameter: Object {apple: 1, orange: 1}
*/

//Example 5: Count how many words are not repeated in an array
var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];

function getWordCnt() {
    return arr.reduce(function (prev, next) {
        console.log(prev, next);
        prev[next] = (prev[next] + 1) || 1;  //Modify this prev
        return prev;//The returned value, which is the value of the prev for the next loop, extends this prev to any type essentially beyond the type set by the initialValue
    }, {});
}
console.log(getWordCnt());

Object {} "apple"
Object {apple: 1} "orange"
Object {apple: 1, orange: 1} "apple"
Object {apple: 2, orange: 1} "orange"
Object {apple: 2, orange: 2} "pear"
Object {apple: 2, orange: 2, pear: 1} "orange"
Object {apple: 2, orange: 3, pear: 1}

reduceRight

Array.prototype.reduceRight(r,v) is a right-to-left version of Array.prototype.reduce.
var matrix = [
  999,
  [3, 4],
  [5, 6]
];

var flatten = matrix.reduceRight(function (previous, current) {
    console.log(previous, current);
    if (!Array.isArray(previous)) {
        previous = Array.of(previous);
    }
    return previous.concat(current);
});
/*
[5, 6] [3, 4]
[5, 6, 3, 4] 999
*/

forEach

Array.prototype.forEach(fn,context),val, index, arr
[1, 2, 'str', ['a'], true].forEach(function (val, index, arr) {
    if (val) {
        console.log(val, index)
    }
})
/*
1 0
2 1
str 2
["a"] 3
true 4
*/
{a:1,b:2}.forEach(function(val,index,obj){if(val){console.log(val)}})//object error

map

Array.prototype.map(fn,context),

So there must be a return in fn, and the parameter must be val,index,array.This FN can be customized or a js built-in method such as Math.sqaure uses the function fn to modify each element, collect each return value of f sequentially, and return this newly formed array.

//Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
//First, each word is converted to its corresponding plural form.
function fuzzyPlural(single) {
  var result = single.replace(/o/g, 'e');  
  if( single === 'kangaroo'){
    result += 'se';
  }
  return result; 
}
var words = ["foot", "goose", "moose", "kangaroo"];
console.log(words.map(fuzzyPlural));

// ["feet", "geese", "meese", "kangareese"]

//Second, find the square root of each element in the array
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
/* roots The value of [1, 2, 3], and the value of numbers is still [1, 4, 9] */

//Third:String  Use on map Method gets the corresponding for each character in the string ASCII Array of codes:
var map = Array.prototype.map
var a = map.call("Hello World", function(x) { return x.charCodeAt(0); })
// The value of a is [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

//Fourth, in general, the FN function in the map method only accepts one parameter, the array element itself being traversed.This does not mean that map passes only one parameter to fn.This mental inertia can make us make a very easy mistake.

// What does the following statement return?
["1", "2", "3"].map(parseInt);
// You might think [1, 2, 3]
// But the actual result is [1, NaN, NaN]

// Usually, when parseInt is used, only one parameter needs to be passed. In fact, parseInt can have two parameters. The second parameter is a binary number. It can be verified by the statement "alert(parseInt.length)===2".
// When the map method calls the callback function, it passes three parameters: the element being traversed, the element index, and the original array itself.
// The third parameter, parseInt, is ignored, but the second parameter is not, that is, parseInt uses the index value passed in as a binary number, returning NaN.

/*
//The following user function, returnInt, should be used

function returnInt(element){
  return parseInt(element,10);
}

["1", "2", "3"].map(returnInt);
// Return to [1,2,3]
*

Class Array

Authoritative Guide Definition

// Determine if o is an array-like object.Determine if o is a class array object
// Strings and functions have numeric length properties, but are strings and functions have length properties, but they do
// excluded by the typeof test. In client-side JavaScript, DOM text can be excluded by typeof detection, in client js, DOM text node
// nodes have a numeric length property, and may need to be excluded also have a length property, requiring extra judgment of o.nodeType!=3 to exclude it
// with an additional o.nodeType != 3 test.
function isArrayLike(o) {
    if (o &&                                // o is not null, undefined, etc. o is not null undefined, etc.
        typeof o === 'object' &&            // o is an object o is an object
        isFinite(o.length) &&               // o.length is a finite number o.length is a finite number
        o.length >= 0 &&                    // O.length is non-negative o.length is non-negative
        o.length===Math.floor(o.length) &&  // o.length is an integer o.length is an integer
        o.length < 4294967296)              // O.length < 2^32 o.length less than 2^32
        return true;                        // Then o is array-like
    else
        return false;                       // Otherwise it is not //Otherwise it is not an array of classes
}

Use of generic class arrays

1: Yes {contains length key-value pairs} 2:[] are class arrays

//1:{Key-value pairs with length attribute}
isArrayLike({qq:"aa",ww:"bbb",ss:"ccc",length:3})//true
isArrayLike({"0":"aa",1:"bbb",2:"ccc",length:3})//true special class array
//2:[] Ordinary Array
isArrayLike([])//true

Special class array

Use class arrays like arrays (the object's properties are "numeric" strings,'0''1''2''3'....)

/*
Because of these"{ Key-value pairs with the length attribute}"Class array objects are not constructed from the new Array() constructor, so they do not have the prototype methods of Array.
But we can use array methods such as [].map.call({},fn),[].slice.call({},..) to change the scope.
If you want to use them like arrays, in addition to the length attribute, you need to do this:
You need to ensure that the property of this object must be a numeric string.'0' '1' '2' '3'....
*/

[].map.call({0:"aa",1:"bbb",2:"ccc",length:3},function(val){return val+"ooooooo"})//["aaooooooo", "bbbooooooo", "cccooooooo"]

//Common function: converting class array objects into arrays
[].slice.call({0:"aa",1:"bbb",2:"ccc",length:3},0)//["aa", "bbb", "ccc"]

Array of classes in normal development arguments Nodelist

/*
Be careful:
The function's built-in object, arguments, is itself an array of classes and cannot use Array's prototype instance method, but it can be used by changing the scope through call s and so on.
*/

//arguments
a(1,"2")
function a(){
console.log(arguments);//[1,'2'], the print here is [], it looks like an array, but the expanded image below is not the same as an ordinary array.
//Console.log (arguments.slice()//This will result in an error: Uncaught TypeError: arguments.slice is not a function
console.log([].slice.call(arguments));//[1, "2"]
}

console.log([].slice.call({0:"a",1:"bbb",2:"ccc",str:"str",str2:"str2",length:5}))//slice removes an array of classes whose attributes are not numbers

//NodeList
var falseArr=document.getElementsByTagName('div');
for(item in falseArr)console.log(item)//As you can see, item is 0 1 2 3... there are also some ID classes and so on, proving that NodeList is an array of classes
//falseArr.slice()//Error
console.log([].slice.call(falseArr))

screenshot

String as Array

var str="asfwefwgw";
for(i=0; i<str.length;i++){console.log(i)}
for(i=0; i<str.length;i++){console.log(str[i])}

Array.from(arrayLike,[fn])

From a class array, set, Map (traversable) to an array
//Array of special classes (keys are numbers)
var o={"0":"aa",1:"bbb",2:"ccc",length:3};Array.from(o);//["aa", "bbb", "ccc"]

//General Class Array
var o={qq:"aa",ww:"bbb",ss:"ccc",length:3};Array.from(o);//[undefined, undefined, undefined]
//The class array nodeList cannot use the array instance method directly. To call apply change the scope
var nodes=document.getElementsByTagName('a');
// nodes.forEach(function(val,key){console.log(key);})//nodes.forEach is not a function
//es5
//Array.prototype.forEach.call ,[].forEach.call
[].forEach.call(nodes,function(val,key){console.log(key);})
//es6
var nodesArray=Array.from(nodes);
nodesArray.forEach(function(val,key){console.log(key);})
//Class array arguments cannot use the array instance method directly. Callapply must change the scope before it can
function foo(){
    //arguments.forEach(function(val,index){console.log(index)})//arguments.forEach is not a function
        Array.prototype.forEach.call(arguments,function(val,index){console.log(index)})//1,2,3
    Array.from(arguments).forEach(function(val,index){console.log(index)})//1,2,3
}
foo(1,2,3)
//String
//Set
//Map

Array compatible with lower version IE extensions

if (typeof Array.prototype.forEach != "function") {
  Array.prototype.forEach = function (fn, context) {
    for (var k = 0, length = this.length; k < length; k++) {
      if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) fn.call(context, this[k], k, this);
    }
  };
}

if (typeof Array.prototype.map != "function") {
  Array.prototype.map = function (fn, context) {
    var arr = [];
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {
          arr.push(fn.call(context, this[k], k, this));
      }
    }
    return arr;
  };
}

if (typeof Array.prototype.filter != "function") {
  Array.prototype.filter = function (fn, context) {
    var arr = [];
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {
          fn.call(context, this[k], k, this) && arr.push(this[k]);
      }
    }
    return arr;
  };
}

if (typeof Array.prototype.some != "function") {
  Array.prototype.some = function (fn, context) {
    var passed = false;
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {
          if (passed === true) break;
          passed = !!fn.call(context, this[k], k, this);
      }
    }
    return passed;
  };
}

if (typeof Array.prototype.every != "function") {
  Array.prototype.every = function (fn, context) {
    var passed = true;
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {
          if (passed === false) break;
          passed = !!fn.call(context, this[k], k, this);
      }
    }
    return passed;
  };
}

if (typeof Array.prototype.indexOf != "function") {
  Array.prototype.indexOf = function (searchElement, fromIndex) {
    var index = -1;
    fromIndex = fromIndex * 1 || 0;

    for (var k = 0, length = this.length; k < length; k++) {
      if (k >= fromIndex && this[k] === searchElement) {
          index = k;
          break;
      }
    }
    return index;
  };
}

if (typeof Array.prototype.lastIndexOf != "function") {
  Array.prototype.lastIndexOf = function (searchElement, fromIndex) {
    var index = -1, length = this.length;
    fromIndex = fromIndex * 1 || length - 1;

    for (var k = length - 1; k > -1; k-=1) {
        if (k <= fromIndex && this[k] === searchElement) {
            index = k;
            break;
        }
    }
    return index;
  };
}

if (typeof Array.prototype.reduce != "function") {
  Array.prototype.reduce = function (callback, initialValue ) {
     var previous = initialValue, k = 0, length = this.length;
     if (typeof initialValue === "undefined") {
        previous = this[0];
        k = 1;
     }
     
    if (typeof callback === "function") {
      for (k; k < length; k++) {
         this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
      }
    }
    return previous;
  };
}

if (typeof Array.prototype.reduceRight != "function") {
  Array.prototype.reduceRight = function (callback, initialValue ) {
    var length = this.length, k = length - 1, previous = initialValue;
    if (typeof initialValue === "undefined") {
        previous = this[length - 1];
        k--;
    }
    if (typeof callback === "function") {
       for (k; k > -1; k-=1) {          
          this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
       }
    }
    return previous;
  };
}

Reference resources:
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
http://www.zhangxinxu.com/wordpress/2013/04/es5%E6%96%B0%E5%A2%9E%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95/


Posted by 7awaka on Mon, 08 Jul 2019 11:56:04 -0700