Apply and array: Three Tips

Source: Internet
Author: User
Apply Method

Apply is a method available to all functions.. Its signature is as follows:

func.apply(thisValue, [arg1, arg2, ...])

If thisValue is not taken into account, The above call is equivalent:

func(arg1, arg2, ...)

That is to say,Apply allows us to "Unbind" an array into parameters and pass them to the call function.. Let's take a lookThree Tips for using apply.

Tip 1: pass an array to a function that does not accept an array as a parameter

JavaScript does not return the maximum value of an array. However, there is a function.Math. max returns the maximum value of any number of numeric values..Apply, We can achieve our goal:

> Math.max.apply(null, [10, -1, 5])10

Note: if one of the parameters of the Math. max method is converted to NaN, the method returns NaN directly.

> Math. max (1, null) // equivalent to Math. max (1, 0) 1> Math. max (1, undefinded) // equivalent to Math. max (1, NaN) NaN> Math. max (0,-0) // The ratio of positive to zero is greater than that of negative to zero, and the value = is different. 0> Math. max (-0,-1) // negative zero ratio-1 large-0
Tip 2: fill gaps in sparse array Arrays

In JavaScript, an array is a ing between numbers and values. Therefore, if an element (a gap) is missing at an index and the value of an element isUndefinedThere are two different situations.Related methods in Array. prototype(ForEach,Map) The traversal will skip the missing elements, and the latter will not:

> ["a",,"b"].forEach(function (x) { console.log(x) })ab> ["a",undefined,"b"].forEach(function (x) { console.log(x) })aundefinedb

Note: here the author says, "array is a ing between numbers and values", which is strictly incorrect. The correct statement is that "array is a ing between strings and values ". the following is evidence:

> For (I in ["a", "B"]) {console. log (typeof I) // the index of the array is actually a string} "string" "string"> ["a", "B"]. forEach (function (x, I) {console. log (typeof I) // here I is not actually an index, but a number type accumulators}) "number" "number"

You can useIn operator to detect gaps in the array.

> 1 in ["a",,"b"]false > 1 in ["a", undefined, "b"]true

Note: here we can use 1 because the in operator converts 1 to "1 ".

If you try to read the value of this gap, it will returnUndefined, and actualThe undefined element is the same.

> ["a",,"b"][1]undefined> ["a", undefined, "b"][1]undefined

Note: [1] will also be converted to ["1"]

Fill gaps

ApplyArray(New is not required here), you can fill the gaps in the arrayUndefinedElement:

> Array.apply(null, ["a",,"b"])[ 'a', undefined, 'b' ]

This is becauseApply does not ignore gaps in the array, Uses the gapUndefinedParametersPass to function:

> function returnArgs() { return [].slice.call(arguments) }> returnArgs.apply(null, ["a",,"b"])[ 'a', undefined, 'b' ]

However, note that ifThe parameter received by the Array method is a separate number. This parameter is treated as the Array length and a new Array is returned.:

> Array.apply(null, [ 3 ])[ , ,  ]

Therefore, the most reliable method is to write such a function to do this job:

function fillHoles(arr) {    var result = [];    for(var i=0; i < arr.length; i++) {        result[i] = arr[i];    }    return result;}

Run:

> fillHoles(["a",,"b"])[ 'a', undefined, 'b' ]

In Underscore_. CompactThe function removes all dummy values from the array, including gaps:

> _.compact(["a",,"b"])[ 'a', 'b' ]> _.compact(["a", undefined, "b"])[ 'a', 'b' ]> _.compact(["a", false, "b"])[ 'a', 'b' ]
Tip 3: Flat Arrays

Task: convert an array containing multiple array elements into a first-order array.Combination of apply's ability to unpack ArraysConcat to do this:

> Array.prototype.concat.apply([], [["a"], ["b"]])[ 'a', 'b' ]

You can also mix non-array elements:

> Array.prototype.concat.apply([], [["a"], "b"])[ 'a', 'b' ]

ApplyMethodThisValue must be specified[]BecauseConcat is an array methodIs not an independent function. The limit of this writing method is that it can only flat second-order arrays at most:

> Array.prototype.concat.apply([], [[["a"]], ["b"]])[ [ 'a' ], 'b' ]

Therefore, you should consider an alternative. For example, the _. flatten function in Underscore can process nested arrays of any number of layers:

> _.flatten([[["a"]], ["b"]])[ 'a', 'b' ]


http://www.2ality.com/2012/07/apply-tricks.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.