English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Обычные логические задачи в JavaScript и их решения

统计数组 arr 中值等于 item 的元素出现的次数

function count(arr, item) {
   var count = 0;
   arr.forEach(function(e){
     //e для каждого элемента arr, равного item, count+1
     e == item ? count++ : 0;
   });
   return count;
 }
function count(arr, item) {
  return arr.filter(function(a){
    return (a==item);
  }).length
}
function count(arr, item) {
var res;
return (res = arr.toString().match(new RegExp("//b"+item+"//b","g")))?res.length:0;
}
function count(arr, item) {
      var count = 0;
      arr.map(function(a) {
        if(a === item) {
          count++;
        }
      });
      return count;
    }

2, для каждого элемента массива arr вычислить квадрат. Не изменяйте массив arr напрямую, результат возвращает новый массив

function square(arr) {
  return arr.map(function(item,index,array){
    return item*item;
  }
}
function square(arr) {
  //декларация нового массива для хранения результатов
   var a = [];
   arr.forEach(function(e){
     //всех элементов arr взяв квадрат, добавляем в массив a
     a.push(e*e);
   });
   return a;
 }
function square(arr) {
//копируем массив arr
  var newarr = arr.slice(0);
  for (var i=0;i<newarr.length;i++){
    newarr[i]= newarr[i]* newarr[i];
  }
  return newarr;
}
function square(arr) {
  return arr.map(function(item){
    return Math.pow(item, 2);
  }
}

3、параметры массива arr передаются в качестве аргументов при вызове функции fn

function argsAsArray(fn, arr) {
 return fn.apply(this, arr);
 }
function argsAsArray(fn, arr) {
  return function(para1,para2){ 
    return para1.apply(this,para2);
  }(fn,arr);
}

Четыре, завершите функцию createModule, после чего она должна соответствовать следующим требованиям:

     1、возвращает объект

     2、значение свойства greeting объекта равно str1, значение свойства name равно str2

     3、объект имеет метод sayIt, который возвращает строку greeting属性的 значения + ‘, ‘ +name属性的 значения

function createModule(str1, str2) {
   var obj = {
     greeting : str1,
     name   : str2,
     sayIt  : function(){
       //два свойства перед этим должны быть добавлены с помощью this
       return this.greeting+", "+this.name;
     }
   };
   return obj;
 }
// Use constructor method
function createModule(str1, str2) {
  function Obj() {
    this.greeting = str1;
    this.name = str2;
    this.sayIt = function() {
      return this.greeting + ', ' + this.name;
    };
  }
  return new Obj();
}
// Combine constructor and prototype
function createModule(str1, str2) {
  function CreateMod() {
    this.greeting = str1;
    this.name = str2;
  }
  CreateMod.prototype.sayIt = function() {
    return this.greeting + ', ' + this.name;
  }
  return new CreateMod();
}

Five, given fn is a predefined function, implement the function curryIt, after calling it, it meets the following conditions:

      1. Return a function a, the length property value of a is 1 (i.e., explicitly declare a to accept one parameter)

      2. After calling a, return a function b, the length property value of b is 1

      3. After calling b, return a function c, the length property value of c is 1

      4. After calling c, the result returned is consistent with the return value of calling fn

      5. The parameters of fn are the call parameters of the functions a, b, c in turn

Input example:

var fn = function (a, b, c) {return a + b + c}; curryIt(fn)(1)(2)(3);
function curryIt(fn) {
   // Get the number of fn parameters
   var n = fn.length;
   // Declare an array args
   var args = [];
   // Return an anonymous function
   return function(arg) {
     // Put the parameters in the brackets after curryIt into the array
     args.push(arg);
     // If the number of arguments in args is less than the number of arguments in fn function,
     // Then execute arguments.callee (which refers to the currently executing function, here the returned anonymous function).
     // Otherwise, return the result of the fn call
     if (args.length < n) {
      return arguments.callee;
     } else return fn.apply("", args);
   }
 }
function curryIt(fn) {
  return function a(xa) {
    return function b(xb) {
      return function c(xc){
        return fn.call(this,xa,xb,xc);
      };
    };
  };
}

Шестой раздел: вывод положения элементов массива

function indexof(arr,item){
  for(var i = 0,len = arr.length;i<len;i++){
    var ite = arr[i];
    if(ite == item){
      console.log(ite == item);
      return i;
    }else{
      return -1;
    }
  }
}
function indexof(arr,item){
  return arr.indexOf(item);
}

Седьмой раздел: сумма массива

function sum(arr) {
  return eval(arr.join("+"));
};

Восьмой раздел: удаление заданного элемента

  function remove(arr, item) {
    for(var i=0, m=arr.length, res=[]; i<m; i++){
      if(item === arr[i]) continue;
      else res.push(arr[i]);
    }
    return res;
  }
function remove(arr, item) {
  var newA=arr.slice(0);
  for(var i=newA.indexOf(item);i>-1;i=newA.indexOf(item)){
    newA.splice(i,1);
  }
  return newA;
}

Резюме

Обычные логические задачи в JavaScript заканчиваются здесь, не знаете ли вы, выучили ли вы все? Контент этой статьи может быть полезен для вашего обучения или работы, если у вас есть вопросы, вы можете оставить комментарий для обсуждения, спасибо за поддержку учебника呐喊.

Вам может понравиться