Several common js functions
1. Array.foreach () itself does not alter the Array (and cannot alter the Array via assignment) because it does not return a value, passing each element in the Array to the provided function. Similar to for, but without breaking. Question: Why can’t forEach break out of a loop with a break and return? A:
Array.prototype.forEach = function(callback,thisArg){var this.length; for(var i = 0; i < len; i++){ callback.call(thisArg,this[i], i, this); }}Copy the code
Answer: The first argument to forEach is a callback function. Break and return are called by the callback function, and the for loop is wrapped around the callback function. There is no way to operate on the real for body. So there is no way to stop or break the loop except by throwing an exception.
let arr = [0, 1, "stop", 3, 4]; try { arr.forEach(element => { if (element === "stop") { throw new Error("forEachBreak"); } console.log(element); }); } catch (e) { console.log(e.message); // forEachBreak };Copy the code
2.Array.filter() is to pass all elements into the provided function for judgment, without changing the original Array, and return a new Array composed of elements that meet the conditions. (Filter, filter out the array elements that meet the conditions to form a new array, and return)
Array.prototype.filter = function(fn){ let newArr = []; for(let i=0; i< this.length; i++){ let flag = fn (this[i]); flag&&newArr.push(this[i]) return newArr; }}Copy the code
- Array.map() does not change the Array itself (but can change the Array by reassigning) because map returns a new Array whose elements are the same length as the original Array.
Array.prototype.myMap = function(fn){ var len = this.length; var arr = []; // Create a new array for(var I = 0; i < len; i ++){ arr.push(fn(this[i],i)) } return arr; }Copy the code
thinking
1. Impact caused by prototype, prototype chain, prototype object and modification of prototype chain
2. This points to the problem
3. Break, return and continue
other
Brief introduction to the understanding of Css preprogramming language? What are the differences?