前端面の上にブラシをノート(XII)

スタックオーバーフロー1.以下の再帰関数の危険性があり、どのように最適化しますか?

function factorial(n){
    return n*factorial(n-1)
}

回答:

function factorial(n){
    return n > 1 ? n * factorial(n-1) : 1;
}

2.最大公約数関数の計算を実装します。

function greatestCommonDivisor(a,b){
//在这里编写代码
}
greatestCommonDivisor(8, 12) //4
greatestCommonDivisor(8, 16) //8
greatestCommonDivisor(8, 17) //1

回答:

function greatestCommonDivisor(a,b){
  var num=0;  
      while(b!=0){       
           num=a%b;  
           a=b;  
           b=num;  
      }  
      return a;

}

3.重複排除アレイ(アレイNaNである場合)

Array.prototype.uniq = function () {
   var resArr = [];
   var flag = true;
      
   for(var i=0;i<this.length;i++){
       if(resArr.indexOf(this[i]) == -1){
           if(this[i] != this[i]){   

               //排除 NaN
              if(flag){
                   resArr.push(this[i]);
                   flag = false;
              }
           }else{
                resArr.push(this[i]);
           }
       }
   }
    return resArr;
}

4.には、JavaScriptをn番目のフィボナッチ数を返しフィボナッチ列関数を使用して実装しました。F(1)= 1、F(2)= 1、等

function fibonacci(n) {
    if(n ==1 || n == 2){
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

パッケージ名は、指定された空間内のオブジェクトを作成します

説明を入力します。

名前空間({:{テスト:1、B:2}}、 'ABCD')

出力説明:

{{テスト:1、B:{C:{D:{}}}}}

function namespace(oNamespace, sPackage) {
 
    var properties = sPackage.split('.');
    var parent = oNamespace;
 
    for (var i = 0, lng = properties.length; i < lng; ++i) {
 
        var property = properties[i];
 
        if (Object.prototype.toString.call(parent[property])!== '[object Object]') {
            parent[property] = {};
        }
 
        parent = parent[property];
 
    }
 
    return oNamespace;
 
}

前記ラッパー関数f、F、これは指定されたオブジェクトを参照するように

function bindThis(f, oTarget) {
    return function(){
        var parames = Array.prototype.slice.call(arguments);
        return f.apply(oTarget,parames); //注意这里需要返回f的执行结果
    }  
}

7.domノードを検索

共通の親に最も近い二つのノードを検索し、ノード自体を含むことができ

説明を入力します。

oNode1とoNode2同じ文書で、それは同じノードではありません

function commonParentNode(oNode1, oNode2) {
    if(oNode1.contains(oNode2)){
        return oNode1;
    }else if(oNode2.contains(oNode1)){
        return oNode2;
    }else{
        return commonParentNode(oNode1.parentNode,oNode2);
    }
}

8.リレーショナルオブジェクトのアレイは、ツリー構造に変換されます

リレーショナル配列:

var obj = [
    { id:3, parent:2 },
    { id:1, parent:null },
    { id:2, parent:1 },
]

期待される結果:

o = {
  obj: {
    id: 1,
    parent: null,
    child: {
      id: 2,
      parent: 1,
      child: {
          id: ,3,
          parent: 2
      }
    }
  }
}

実装のソースコード:

function treeObj(obj) {
  obj.map(item => {
    if (item.parent !== null) {
      obj.map(o => {
        if (item.parent === o.id) {
          if (!o.child) {
            o.child = [];
          }
          o.child.push(item);
          o.child = o.child;
        }
      });
    }
  });
  return obj.filter(item => item.parent === null)[0]
}

または:

function treeObj(obj) {
  return obj.sort((a, b) => b.parent - a.parent)
      .reduce((acc, cur) => (acc ? { ...cur, child: acc } : cur));
}

どのように9.JSは、連続した数字のセットかどうかを判断します

// 当出现连续数字的时候以‘-’输出
[1, 2, 3, 4, 6, 8, 9, 10]

期待される結果:

["1-4", 6, "8-10"]

実装コード:

連続するかどうかを決定します。

var arrange = function(arr){
    var result = [],temp = [];
    arr.sort(function(source, dest){
        return source - dest;
    }).concat(Infinity).reduce(function(source, dest){
        temp.push(source);
        if(dest-source > 1){
            result.push(temp);
            temp = [];
        }
        return dest;
    });
    return result;
};

フォーマットは達成します:

var formatarr = function(arr) {
    var newArr = []
    var arr1 = arrange(arr)
    for (var i in arr1) {
        var str = '';
        if (arr1[i].length > 1) {
            str = arr1[i][0] + '-' + arr1[i][arr1[i].length - 1];
            newArr.push(str)
        } else {
            newArr.push(arr1[i][0]);
        }
   }
   return newArr;
}

10.親クラスのメソッドの子供、プロトタイプやコンストラクタのサブクラスを作成して人々の道を継承し、彼の名前と年齢を与えることを言う関数を呼び出します。

親クラス:

function People(name,age){
     this.name=name;
     this.age=age;
     this.say=function(){
         console.log("我的名字是:"+this.name+"我今年"+this.age+"岁!");
     };
}

プロトタイプの継承:

function Child(name, age){
    this.name = name;
    this.age = age;
}
Child.prototype = new People();
var child = new Child('Rainy', 20);
child.say()

コンストラクタの継承:

function Child(name, age){
    People.call(this)
    this.name = name;
    this.age = age;
}
var child = new Child('Rainy', 20);
child.say()

継承の組み合わせ:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = People.prototype;
var child = new Child('Rainy', 20);
child.say()

継承の最適化の組み合わせ:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = Object.create(People.prototype);
Child.prototype.constructor = Child;
var child = new Child('Rainy', 20);
child.say()

ようこそ注意

おすすめ

転載: blog.csdn.net/weixin_40659167/article/details/87654302