JS

javascript

要宣告function,不要丟在ready裡面,要放在外面,這樣才存取得到。

詳細、新

參考資料:(https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part4/event.html)

比對

模糊比對 *= // 類似SQL "%value%" 後綴比對 $= // 類似SQL "%value"

selector

參考資料:(https://api.jquery.com/category/selectors/)

jQuery .prop() 設值

$("input[name=background][value='some value']").prop("checked",true);

Math.ceil() 無條件進位成整數

不回傳值 javascript:void(0)

參考資料:(http://www.runoob.com/js/js-void.html)

javascript:void(0)

javascript:void(0) 中最关键的是 void 关键字, void 是 JavaScript 中非常重要的关键字,该操作符指定要计算一个表达式但是不返回值。

void(0)
void(alert("www"))

因為void 不回傳值,所以放在href裡面,可以當成無效的連結,但是()內的東西還是會發生,例如第二行,就會跳出提示窗。

this

參考資料:(https://software.intel.com/zh-cn/blogs/2013/10/09/javascript-this)

不管方法在哪裡,是誰的方法,只要直接呼叫方法,this就是全域物件。

只要是 _.方法,this 就是 _

比如說

var x = 10;
var obj = {
    x = 20;
    f:()=>{
        console.log(this.x);
    }
};

var obj2 = {
    x = 30;
    f:obj.f
}

var obj3 = obj.f;

obj.f(); //20
obj2.f(); //30
obj3(); //10

指定this給方法

有個方法可以更動前兩種敘述所讓this指派的值,就是利用call與apply。call與apply都是呼叫該函式並讓該函式的this指向給予call或apply的第一個參數。至於call和apply的差別則是在於其後面給予被調用之函式的參數放入的方法不同,一個是直接攤平放在第二個以後的參數;一個是直接放入一個裡面放要給予之參數的陣列。底下一樣看一下公式和範例:

(A物件.)函式.call(B物件,參數1,參數2,參數3, ......); //函式的this指向B物件(若B物件為null,則指向全域物件)
(A物件.)函式.apply(B物件,[參數1,參數2,參數3, ......]); //函式的this指向B物件(若B物件為null,則指向全域物件)

滑出效果

參考資料:(http://abgne.tw/jquery/apply-jquery/slide-q-and-a-list.html)

.hover 滑鼠經過的事件 .click 點擊事件 .slideToggle 展開(若已經展開則收合)

$(function(){
    // 幫 seletor 加上 hover 及 click 事件
    // 同時把兄弟元素 div.qa_content 隱藏起來
    $('seletor').hover(function(){
        $(this).addClass('className');
    }, function(){
        $(this).removeClass('className');
    }).click(function(){
        // 當點到標題時,若答案是隱藏時則顯示它;反之則隱藏
        $(this).slideToggle();
    });
});

.hover 滑鼠經過的事件

可以直接從CSS控制

indexOf() 建議都換成字串

display

參考資料:(http://zh-tw.learnlayout.com/display.html)

屬性名稱:display 常用的值:block、inline、none

各種奇怪的JS bug

參考資料:(https://read01.com/zh-tw/EaNe8.html#.WytteKczYdV)

前一個、下一個

前一個:.prev() 下一個:.next()

導向語法

參考資料:(https://stackoverflow.com/questions/4744751/how-do-i-redirect-with-javascript)

window.location = "http://www.yoururl.com";

利用連結觸發事件

<a href="javascript:functionName();">text</a>

confirm 通知訊息窗可以是、否

參考資料:(https://www.w3schools.com/jsref/met_win_confirm.asp)

此方法會根據使用者點擊的內容,回傳true、false

let b = confirm("Press a button!"); //return true、false

.tiff 主流瀏覽器中僅被 safari & IE support

location.href 取得當前網址

參考資料:(http://function1122.blogspot.com/2008/04/javascript.html)

參考資料:(http://www.wibibi.com/info.php?tid=82)

.sort()

.sort() 字串排序 .reverse() 反轉 (合併起來用、即為倒序)

.sort(function(a,b){return a - b}) 數字排序 .sort(function(a,b){return b - a}) 數字倒序

arr3 = arr1.concat(arr2)

參考資料:(https://xyz.cinc.biz/2012/12/javascriptmerge.html)

陣列合併,不會去除重複值

若要去除,請查看參考資料

Array.isArray(object)

參考資料:(https://msdn.microsoft.com/zh-tw/library/ff848265(v=vs.94).aspx)

判斷是否為陣列

Math.abs() 傳回絕對值

參考資料:(http://www.victsao.com/blog/81-javascript/255-javascript-math-abs)

parseInt() 確認為Int

arr.join(str)

參考資料:(https://www.w3schools.com/jsref/jsref_join.asp)

將陣列合併成字串,並用 str 做分隔

arr.toString() 等於 arr.join(",")

setInterval(()=>{},毫秒)

setInterval(()=>{ console.log(123); },1000);

clearInterval( setInterval 的 函式物件 )

var timer = setInterval(()=>{console.log(123);},1000);
clearInterval(timer);

陣列的處理

Array.push(item)

將 item 放入 array

Array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start : 要從第幾個索引開始 deleteCount : 將 start 之後的幾個索引刪去 item1... : 將這些物件插入到 start 之後

array.indexOf(item)

檢查該 item 是否存在於 array

陣列的處理方法

參考資料:(https://wcc723.github.io/javascript/2017/06/29/es6-native-array/#Array-prototype-filter)

// 相同的陣列
var people = [
  {
    name: 'Casper',
    like: '鍋燒意麵',
    age: 18
  },
  {
    name: 'Wang',
    like: '炒麵',
    age: 24
  },
  {
    name: 'Bobo',
    like: '蘿蔔泥',
    age: 1
  },
  {
    name: '滷蛋',
    like: '蘿蔔泥',
    age: 3
  }
];

Array.prototype.filter()

var filterEmpty = people.filter(function(item, index, array){
});
console.log(filterEmpty);    // 沒有條件,會是一個空陣列
var filterAgeThan5 = people.filter(function(item, index, array){
  return item.age > 5;       // 取得大於五歲的
});
console.log(filterAgeThan5); // Casper, Wang 這兩個物件
var filterDouble = people.filter(function(item, index, array){
  return index % 2 === 1;    // 取得陣列中雙數的物件
});
console.log(filterDouble);   // Wang, 滷蛋 這兩個物件

Array.prototype.find()

find() 與 filter() 很像,但 find() 只會回傳一次值,且是第一次為 true 的值。

var findEmpty = people.find(function(item, index, array){
});
console.log(findEmpty);          // 沒有條件,會是 undefined
var findAgeThan5 = people.find(function(item, index, array){
  return item.age > 5;           // 取得大於五歲的
});
console.log(findAgeThan5);       // 雖然答案有兩個,但只會回傳 Casper 這一個物件
var findLike = people.find(function(item, index, array){
  return item.like === '蘿蔔泥';  // 取得陣列 like === '蘿蔔泥'
});
console.log(findLike);           // 雖然答案有兩個,但只會回傳第一個 Bobo 物件

Array.prototype.forEach()

forEach 是這幾個陣列函式最單純的一個,不會額外回傳值,只單純執行每個陣列內的物件或值。

var forEachIt = people.forEach(function(item, index, array){
  console.log(item, index, array); // 物件, 索引, 全部陣列
  return item;                     // forEach 沒在 return 的,所以這邊寫了也沒用
});
console.log(forEachIt);            // undefined
people.forEach(function(item, index, array){
  item.age = item.age + 1;         // forEach 就如同 for,不過寫法更容易
});
console.log(people);               // 全部 age + 1

Array.prototype.map()

使用 map() 時他需要回傳一個值,他會透過函式內所回傳的值組合成一個陣列。

  • 如果不回傳則是 undefined

  • 回傳數量等於原始陣列的長度

    這很適合將原始的變數運算後重新組合一個新的陣列。

var mapEmpty = people.map(function(item, index, array){
});
console.log(mapEmpty);    // [undefined, undefined, undefined, undefined]
var mapAgeThan5 = people.map(function(item, index, array){
  return item.age > 5;    // 比較大於五歲的
});
console.log(mapAgeThan5); // [true, true, false, false]
var mapAgeThan5_2 = people.map(function(item, index, array){
  // 錯誤示範
  if (item.age > 5) {
    return item;              // 回傳大於五歲的
  }
  return false;               // 別以為空的或是 false 就不會回傳
});
console.log(mapAgeThan5_2);   // [{name: 'Casper'...}, {name: 'Wang'...}, false, false]
var mapEat = people.map(function(item, index, array){
  if (item.like !== '蘿蔔泥') {
    return `${item.like} 好吃`;
  } else {
    return `${item.like} 不好吃`;
  }
});
console.log(mapEat);          // ["鍋燒意麵 好吃", "炒麵 好吃", "蘿蔔泥 不好吃", "蘿蔔泥 不好吃"]

Array.prototype.every()

every() 可以檢查所有的陣列是否符合條件,這僅會回傳一個值 true or false,可以用來檢查陣列中的內容是否符合特定條件。

var array = [
  {
    name: 'Casper',
    like: '鍋燒意麵',
    age: 18
  },
  {
    name: 'Wang',
    like: '炒麵',
    age: 24
  },
  {
    name: 'Bobo',
    like: '蘿蔔泥',
    age: 1
  },
  {
    name: '滷蛋',
    like: '蘿蔔泥',
    age: 3
  }
];
var ans = array.every(function(item, index, array){
  console.log(item, index, array); // 物件, 索引, 全部陣列
  return item.age > 10 // 當全部 age 大於 10 才能回傳 true
});
console.log(ans); // false: 只要有部分不符合,則為 false
var ans2 = array.every(function(item, index, array){
  return item.age < 25
});
console.log(ans2); // true: 全部 age 都小於 25

Array.prototype.some()

some()every() 非常接近,都是回傳 true or false,差異僅在 every() 需完全符合,some() 僅需要部分符合。

var ans = people.some(function(item, index, array){
  return item.age > 10 // 當全部 age 大於 10 才能回傳 true
});
console.log(ans);  // true: 只要有部分符合,則為 true
var ans2 = people.some(function(item, index, array){
  return item.age < 25
});
console.log(ans2); // true: 只要有部分符合,則為 true  
var ans2 = people.some(function(item, index, array){
  return item.age > 25
});
console.log(ans2); // false: 全部都不符合則為 false

Array.prototype.reduce()

reduce() 和其他幾個差異就很大了,他可以與前一個回傳的值再次作運算,參數包含以下:

  • accumulator: 前一個參數,如果是第一個陣列的話,值是以另外傳入或初始化的值

  • currentValue: 當前變數

  • currentIndex: 當前索引

  • array: 全部陣列

var reduceEmpty = people.reduce(function(accumulator, currentValue, currentIndex, array){
});
console.log(reduceEmpty);                 // 沒有條件,會是 undefined
var reducePlus = people.reduce(function(accumulator, currentValue, currentIndex, array){
  // 分別為前一個回傳值, 目前值, 當前索引值
  console.log(accumulator, currentValue, currentIndex);
  return accumulator + currentValue.age;  // 與前一個值相加
}, 0);                                    // 傳入初始化值為 0
console.log(reducePlus);                  // 總和為 46
var reducePlus = people.reduce(function(accumulator, currentValue, currentIndex, array){
  console.log('reduce', accumulator, currentValue, currentIndex)
  return Math.max( accumulator, currentValue.age ); // 與前一個值比較哪個大
}, 0);
console.log(reducePlus);                  // 最大值為 24

其它

預設的陣列行為內的 this 是指向 window (本篇中除了 reduce() 是傳入初始資料),如果要改,可以在 function 後傳入。

// arr.forEach(function callback(currentValue, index, array) {
// your iterator
// }[, thisArg]);
var ans3 = people.forEach(function(item, index, array){
  console.log(this) // 這邊的 this 就會使用後方傳入的
  return item.age < 25
}, people);         // 傳入的物件,替代 this,如果無則是 window

如何將物件組成queryString

Object.keys(payload) 會回傳陣列 ["param1", "param2", "param3", "notImportant", "blablabla"]

Object.keys(payload) .filter(key => key.includes('param')) .map(key=> ${key}=${payload[key]} ) .join('&')

param1=10&param2=20&param3=30 大功告成!

跳轉

參考資料:(https://clifflin123456.pixnet.net/blog/post/44902693-%E5%88%A9%E7%94%A8-javascript-%E4%B9%8B-location.href-or-window.location-%E9%80%B2)

參考資料:w3c-location(https://www.w3schools.com/jsref/obj_location.asp)

參考資料:中文詳細解釋 w3c 的內容(http://cat-son.blogspot.com/2012/11/javascript-windowlocation.html#sthash.W7qz9xAm.dpbs)

設屬性去跳轉

window.location = "url"
window.location.href = "url"
location = "url"
location.href = "url";

方法跳轉

window.location.assign("url"); //A B assign C 上一頁 會回到B
window.location.replace("url");  //A B replace C 上一頁 會回到A

取得參數

window.location.search 可以取得 QueryString
window.location.hash  可以取得 錨點(anchor) // # 之後的都會被視為 hash,所以正常會放在 QueryString 後面

重讀頁面

window.location.reload(forceGet) forceGet 預設為 false,代表從 Cache 重新載入 如果設為 true,則會跟 Server 重新要資料

取得元素的座標

參考資料:(https://andyyou.github.io/2015/04/07/get-an-element-s-position-by-js/)

用 JavaScript 來取得表單元素內容的值(取值)

參考資料:(https://pjchender.blogspot.com/2015/11/javascript.html)

使用 getElementById

getElementsByTagName

getElementsByName

利用form取得元素

function processFormData() {
  const form = document.forms['form'];    // 取得 name 屬性為 form 的表單
  const name = form.elements.name.value;  // 取得 elements 集合中 name 屬性為 name 的值
  const email = form.elements.email.value;// 取得 elements 集合中 name 屬性為 email 的值
  alert("你的姓名是 " + name + "\n電子郵件是 " + email);
}

Last updated