One question a day, keep thinking

The title

Implement the includes function to determine whether the current array contains the values passed in.

includes([1.2.3].1); // true
includes([1.2.3.NaN.3.6].NaN.0); // true
Copy the code

The specific implementation

/ / integer
function toInt(num) {
  var resNum = num % 1;
  if (resNum) {
    num = num - resNum;
    Math.abs(resNum) > 0.5 && (resNum > 0 ? num ++ : num--);
  }
  return num;
}

// Numeric type
function toNumber(num) {
  if (typeofnum ! = ='number'|| num ! == num || (num ===Infinity || num === -Infinity)) {
    num = 0;
  }

  num = toInt(num);
  return num;
}

function includes(array, value, fromIndex) {
  var length = isArray(array) ? array.length : 0;
  if(! length)return false;

  fromIndex = toNumber(fromIndex);
  fromIndex = fromIndex > -1 ? fromIndex : fromIndex + length;


  var index = -1 + fromIndex;

  while(++index < length) {
    if(array[index] === value || (array[index] ! == array[index] && value ! == value)) {return true; }}return false;
}
Copy the code

Implementation approach

Parameters:

  1. array(Array) : The Array to be queried;
  2. value(*) : the value to be searched;
  3. fromIndex(Number) : start position of query;

Steps:

  1. Judge currentarrayParameter is an array and determines the length of the array.
  2. fromIndexPerform type determination to determine whether the type is numeric, if not, assign a value of 0. Because there may be decimal numbers in the numeric type, so the decimal is rounded, and here we use the method of mod to deal with it;
  3. Used herewhileTraversal, first traversal durationindexIs equal to 0, and finallyindexThe value of is equal to the array length value;
  4. Traverse the number group for member sumvalueValues, and there’s one value that’s a little bit special hereNaNBecause theNaN It’s not equal to itself, so there’s a special judgment here, even if it’sNaNReturns the correct value when present and compared;

If you see something wrong or could be improved, feel free to comment. If you think it’s good or helpful, please like, comment, retweet and share. Thank you