JS 基礎 #1 | 常用

判斷型別 typeof

typeof something;

判斷空值

//falsy values: undefined, null, 0, '', NaN

function isEmpty(x) {
	return !(x || x === 0);
}

var i;
console.log(isEmpty(i)); // true


var j = 0;
console.log(isEmpty(j)); // false

Array 新增值 push, unshift / 刪除值 pop, shift / 取得key(判斷 array 中有沒有該值)indexOf

var arr = ['testMiddle'];

//新增值到最後push() 新增值到最前unshift()
arr.push('testEnd'); //arr = ['testMiddle', 'testEnd'];
arr.unshift('testStart');  //arr = ['testStart', 'testMiddle', 'testEnd'];

//刪除最後值pop() 刪除最前值shift()
arr.pop(); //arr = ['testStart', 'testMiddle']; 
arr.shift(); //arr = ['testMiddle'];

//取得 key,可用來判斷 array 中有沒有該值
arr.indexOf('testMiddle'); // 0
arr.indexOf('testNoWhere'); // -1

for & while 迴圈中斷 continue, break

var arr = ['a', 123, 'b', 'c'];

// continue 跳過這次循環,繼續下一個
for (var i = 0; i < arr.length; i++){
	if (typeof(arr[i]) !== 'string') **continue**;
	console.log(arr[i]); //a, b, c
}

// break 中止這次循環
for (var i = 0; i < arr.length; i++){
	if (typeof(arr[i]) !== 'string') **break**;
	console.log(arr[i]); //a
}

選擇DOM物件

document.querySelector()

document.querySelector('#id'); // DOM object 若有多個,選取第1個
document.querySelector('#id').textContent = 'hello';
document.querySelector('#id').innerHTML = '<p>hi</p>';
document.querySelector('#id').style.display = 'none';

document.getElementById()

document.getElementById('id'); // DOM object 若有多個,選取第1個
// 比 querySelector 快

Event事件

addEventListener(‘eventName’)

document.querySelector('#id').addEventListener('click', functionName);
document.querySelector('#id').addEventListener('click', function(){ ... });

if簡寫式

(x === 0) **?** x = 1 **:** x = 0;

Add Class/Remove Class/Toggle Class

document.querySelector('#id').classList.addClass('active');
document.querySelector('#id').classList.removeClass('active');
document.querySelector('#id').classList.toggle('active');

Zeen is a next generation WordPress theme. It’s powerful, beautifully designed and comes with everything you need to engage your visitors and increase conversions.