js小Tips

1、數組插入/刪除/替換
插入刪除,最常想到的是push,shift
但splice效率會更高

2、多層嵌套if
多層if,且判斷是否爲具體值時,可以改爲switch
但最好用Object方法

if (color) {
  if (color === 'black') {
    A();
  } else if (color === 'red') {
    B();
  } else if (color === 'blue') {
    C();
  } else if (color === 'green') {
    D();
  } else {
    E();
  }
}
var colorObj = {
  'black': A,
  'red': B,
  'blue': C,
  'green': D,
  'yellow': E
};
if (color && colorObj.hasOwnProperty(color)) {
  colorObj[color]();
}

3、undefined,null的區別
undefined是一個全局變量的特殊屬性,typeof 也是 undefined。進行數值運算時,undefined是NaN。
null是一個空的對象, typeof 是 object。進行數值運算時,null返回值是0

null是JavaScript的保留關鍵字,而undefined卻不是
undefined 在JSON中不合法,null合法

undefined 表示一個變量沒有被定義,或者定義了沒有賦值。
null 是用來給變量賦值,表示”沒有值”

JavaScript 會給一個沒有初始化的變量賦予undefined
JavaScript 從不會將值賦爲null,它是被程序員用來指定一個var 沒有值。

都是 false
判斷變量是否爲undefined typeof variable === "undefined"
判斷變量是否爲null variable === null
互相比較 null == undefined // true
null === undefined // false

4、使用同一個方法處理數組和單一元素
只需要先將它們併成一個數組,然後處理這個數據即可。

function printUpperCase(words) {
  var elements = [].concat(words);
  for (var i = 0; i < elements.length; i++) {
    console.log(elements[i].toUpperCase());
  }
}

5、快速檢測小塊代碼效率
快速檢測javascript代碼塊的執行效率,我們可以使用 console 方法,比如 console.time(label) 和 console.timeEnd(label)

console.time("Array initialize");
var arr = new Array(100),
    len = arr.length,
    i;
for (i = 0; i < len; i++) {
    arr[i] = new Object();
};
console.timeEnd("Array initialize");

6、concat
concat() 方法用於連接兩個或多個數組。
不會改變現有的數組,而僅僅會返回被連接數組的一個副本。

7、this

// 1
console.log(this); //指向全局對象也就是window
// 包含了prompt alert confirm方法...

// 2
function test() {
  console.log(this);
  this.method = function inner() {console.log(this)};
}; // 這裏this也是指向全局對象
test();

//3
var obj = new test(); // 因爲用的是構造器,this指向test對象

//4
obj.method(); //方法迫使this指向對象

// 5:使用call或apply迫使this指向明確的值
function foo(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
}

var bar = {};
foo.apply(bar, [1, 2, 3]); //第一個參數爲this
console.log(bar) // 會輸出 a: 1, b: 2, c: 3

foo.call(bar, 4, 5, 6); //同樣的效果
console.log(bar) //也會輸出a: 4, b: 5, c: 6

關於第二個情況例子:

function test() {
  this.arr = [1,2,4];
  this.message = "I am here";
  this.fun = function() {
      this.arr.forEach(function(item) {
        console.log(this.message); //會輸出3次undefined,因爲this指向全局對象
    });
  }
}

var t = new test();
t.fun();

//上面例子中,this不會指向test對象,而指向全局對象

//爲了避免這種情況,可以使用變量存儲器this

//雖然this仍指向全局對象,但是可以使用替代變量

function test2() {
  var self = this;
  self.arr = [1,2,4];
  self.message = "I am here";
    self.fun = function() {
      this.arr.forEach(function(item) {
        console.log(self.message); //會輸出I am here 3次
    });
  }
}


var t2 = new test2();
t2.fun();

8、全局變量

for(var i = 0; i < 10; i++) {
    innerLoop();
}

function innerLoop() {
    // 這是個不同的作用域
    for(i = 0; i < 10; i++) { // 缺少var語句,i指向全局作用域
           console.log("this is will show 10 times and not 100.");//只會輸出10次
    }
}

這個例子中,你以爲會輸出100次,實際只會輸出10次。
過程是,第一次i=0,進入innerLoop,但innerLoop裏的i跟外面i是一個,所以這次進來時,innerLoop的i從0到10執行結束後,返回外面for函數時,i已經變成了10,而不是想象中的1。

9、迭代對象的屬性
可以使用Object.keys、Object.entriees或者for循環

function a() {
  this.a= 1;
  this.b = 2;
}

function child() {
  this.c = 3;
  this.d = 4;
}

//child會繼承自a
child.prototype = new a();

var obj = new child();

for (var property in obj) { //此方法不僅比Object.keys慢,而且還包含父屬性
    console.log(property + ": " + obj[property]);//輸出abcd及值
}

for (var property in obj) { //這會返回適合的鍵,但是仍比Object.keys慢 
    if(obj.hasOwnProperty(property))
        //輸出cd及值
        console.log(property + ": " + obj[property]);
}

//下面兩種都輸出cd及值
Object.keys(obj).map((e) => console.log(`key=${e}  value=${obj[e]}`)); // 最佳的方式
Object.entries(obj).forEach(([key, value]) => console.log(`key=${key} value=${value}`)); // 這也是不錯的方法

10、轉換數字

var num = "123 456"
Number(num); //NaN  不是想象中的123
parseInt(num); //123
parseFloat(num); //123

11、訪問對象的屬性,可以 object.atr 或者 object[‘atr’]

12、 刪除屬性的唯一方法是使用 delete 操作符;設置屬性爲 undefined 或者null 並不能真正的刪除屬性, 而僅僅是移除了屬性和值的關聯。

13、

[] == true ; //false
{} == true ; //false
if([]){
  //true
}
if({}){
  //true
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章