Underscore source code Analysis _javascript Skills

Source: Internet
Author: User

Some years ago it was said that JavaScript is the most underrated programming language, and since the Nodejs came out, the whole-end (all stack/full Stack) concept is rising, and now I'm afraid no one can underestimate it. Javascrip is a Class C language, there is a C language based on the general understanding of JavaScript code, but as a scripting language, JavaScript flexibility is much less than C, which can also cause some difficulties in learning.

One, set

1. The first is a few iterative methods.

_.each = _.foreach = function (obj, iteratee, context) {
iteratee = OPTIMIZECB (iteratee, context);
var i, length;
if (Isarraylike (obj)) {
 for (i = 0, length = obj.length i < length; i++) {
  iteratee (obj[i], I, obj);
else {
 var keys = _.keys (obj);
 for (i = 0, length = keys.length i < length; i++) {
  iteratee (Obj[keys[i]], keys[i], obj);
Chained call return
obj;
 

Es also adds a native foreach () method to an array. The difference is that the each (ForEach) method here can be used for all collections, and the function accepts three parameters (set, iteration function, execution Environment).

The OPTIMIZECB function binds the corresponding execution environment to different iterative methods according to the number of parameters of the iteration function, and the Foreach iterative function also accepts three parameters (values, indexes, sets).

The next step is the for loop call iteration function.

A more elegant way of judging isarraylike in _.map: (with only a For loop)

var keys =!isarraylike (obj) && _.keys (obj),
    length = (keys | | obj). length,
    results = Array (length);
  for (var index = 0; index < length; index++) {
   var currentkey = keys? Keys[index]: index;
   Results[index] = Iteratee (Obj[currentkey], currentkey, obj);
  return results;
  

There are two other special places:

• Divides the collection into class array collections and object collections. The Isarraylike function is used:

JS's maximum exact integer
 var max_array_index = Math.pow (2)-1;
 var isarraylike = function (collection) {
var length = collection!= null && collection.length;
return typeof length = = ' number ' && length >= 0 && length <= max_array_index;
 If the collection has a length property and is a number and is greater than 0 and is less than the largest exact integer, the decision is an array of classes

• Using the _.keys function, object also has the native keys function, which returns an array of attributes that the collection obj can enumerate. Implementation is relatively simple, for in plus hasOwnProperty () method.

--------------------------------------------------------------------------------

The _.map,_.reduce method is similar in principle.

The _.find function is similar to the Array.some (), and the difference is that the first element that causes the iteration to be true is returned instead of the Boolean value as Array.some ().

 _.find = _.detect = function (obj, predicate, context) {
  var key;
  if (Isarraylike (obj)) {
   key = _.findindex (obj, predicate, context);
  } else {
   key = _.findkey (obj, predicate, c Ontext);
  }
  if (key!== void 0 && key!==-1) return Obj[key];
function Createindexfinder (dir) {return
  function (array, predicate, context) {
   predicate = CB (predicate, context);
   var length = array!= null && array.length;
   If Dir is 1,index for 0,index+=1,index positive-order loops/
   //If Dir is -1,index length-1,index + = 1 Reverse-order cycle
   //Judge cyclic condition then use index >= 0 & amp;& Index < length method takes into account two kinds of cyclic methods
   var index = dir > 0 0:length-1;
   for (; index >= 0 && Index < length; index + dir) {
    if (predicate (array[index), index, array) return index;
   }
   return-1;}
 _.findindex = Createindexfinder (1);
 

What is worth learning is that a for loop here can be configured in different cyclic order depending on the parameters passed in.

1. The other methods in the collection are basically based on iterative methods.

_.max = function (obj, iteratee, context) {
var result =-infinity, lastcomputed =-infinity,
  value, computed;
if (iteratee = = null && obj!= null) {
 obj = isarraylike (obj)? obj: _.values (obj);
 for (var i = 0, length = obj.length i < length; i++) {
  value = Obj[i];
  if (value > result) {result
   = value;
  }} or
else {
 iteratee = CB (iteratee, context);
 _.each (obj, function (value, index, list) {
  computed = iteratee (value, index, list);
  if (Computed > lastcomputed | | | computed = =-infinity && result = =-infinity) {result
   = value;
   lastcomputed = Computed
  }}
 );
return result;
 

The Max method is used to find the maximum value in the collection, by iterating through all the items in the list, then comparing the current item and the result item, assigning it to the result item if the current item is greater than the result, and finally returning the result item.

2. Set Conversions to arrays

 _.toarray = function (obj) {
    if (!obj) return [];
    In the case of an array, the Array.prototype.slice.call (This,obj) method is used if
    (_.isarray (obj)) return Slice.call (obj);
    Class Array object, which does not use the slice method, but instead uses the. Map to iterate over the collection, thus returning an array. _.identity the value passed in by this method is equal to the value returned. (mainly for iterations)
    if (isarraylike (obj)) return _.map (obj, _.identity);
    Normal object, an array of property values is returned. return
    _.values (obj);
   

Data type

The STL needs to differentiate vector, list and so on because the different data structure needs or may carry on the different realization, but underscore inside collections and arrays separate is what reason? This also starts with the JavaScript data type, and look at the image below.

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.