iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
自我挑戰組

以網頁呈現資料視覺化系列 第 7

Day7 我想知道它哪裡比我好很多 在你心中它和我有什麼不同

  • JavaScript feature

隨著越來越深入JavaScript,現在所考察和學習到的code已經不是肉眼掃過去就能理解,而且包含著JavaScript這語言本身的特點,因此針對這些較難理解和混淆的部分來作筆記:var、let和const的差異,forEach和map的功能箭頭函式,以及new的概念。

  • var, let and const

大家可以參考這篇,簡單的說就是var會汙染到全域變數(如果在函式外也有宣告),let只在區塊作用域內,也就是 { },const作用區域與let相同,且宣告時需給值,且重新賦值(有例外)。其中所謂var會汙染到全域變數可以參考下面兩個例子

var x = 0;

function f(){
  var x = y = 1; // x is declared locally. y is not!
}
f();

console.log(x, y); // Throws a ReferenceError in strict mode (y is not defined). 0, 1 otherwise.
// In non-strict mode:
// x is the global one as expected
// y leaked outside of the function, though!
var x = 0;  // x is declared global, then assigned a value of 0

console.log(typeof z); // undefined, since z doesn't exist yet

function a() { // when a is called,
  var y = 2;   // y is declared local to function a, then assigned a value of 2

  console.log(x, y);   // 0 2

  function b() {       // when b is called
    x = 3;  // assigns 3 to existing global x, doesn't create a new global var
    y = 4;  // assigns 4 to existing outer y, doesn't create a new global var
    z = 5;  // creates a new global variable z and assigns a value of 5.
  }         // (Throws a ReferenceError in strict mode.)

  b();     // calling b creates z as a global variable
  console.log(x, y, z);  // 3 4 5
}

a();                   // calling a also calls b
console.log(x, z);     // 3 5
console.log(typeof y); // undefined as y is local to function a
  • forEach and map

forEach和map都是array的功能,這邊可以參考這篇,而先看下面這張map的介紹圖(原文):
JS_map
array可以最多將3個參數丟到後面(後兩個是option),而map和forEach的差異在map是回傳值,而forEach是直接作用在該array上。
該篇裡面還介紹array的其他功能像filter、find、every,some等,而這些功能的架構與map相同,都是可以丟value、index和array進去,差異是在回傳的功能如同它的名稱,另外比較特別的是reduce,它丟進去的依序可以是前一個回傳值、目前值、當前索引值、和陣列。

  • =>

=>此符號即所謂箭頭函式,可以參考這篇說明,屏除一些花式的寫法(例如搭配this),簡單說就是會回傳值的function簡潔表示法(有點像Python的lambda),可以將前方的參數丟入後方使用,常搭配像在前段的map中使用。

  • new

new不new主要有兩個差異,new了會呼叫constructor,new了才有this(不然this為window),參考文章中的太複雜,我們可以看以下例子:

function friend(name) {
  this.name = name;
  console.log("what is this? ", this);
}

const friend1 = new friend("Leonard");
//[object Object]
const friend2 = friend("Leonard");
//[object Window]

console.log(friend1.name);
// expected output: "Leonard"
console.log(friend2.name);
// Error: Cannot read properties of undefined (reading 'name')

上一篇
Day6 我承認我是視覺動物
下一篇
Day8 手牽手一步兩步三步四步望著天 看星星一顆兩顆三顆四顆連成線
系列文
以網頁呈現資料視覺化30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言