DEV Community

loading...

ちょっと便利なJavaScript技

dongri profile image D ・1 min read

!!でbool値変換

function Account(cash){
  this.cash = cash;
  this.hasMoney = !!cash;
}

var account = new Account(98);
console.log(account.cash); //98
console.log(account.hasMoney); // true

var emptyAccount = new Account(0);
console.log(emptyAccount.cash); //0
console.log(emptyAccount.hasMoney); // false

+文字列を数値に変換

function toNumber(strNumber){
  return +strNumber;
}

console.log(toNumber("1234")); // 1234
console.log(toNumber("ABC")); //NaN

&& 条件式

if (connected){
  login();
}

// ↑の式のを以下のように書ける
connected && login();

// 以下のようにuserオブジェクトの存在チェックにも
user && user.login();

||でデフォルト値設定

function User(name, age) {
    this.name = name || "Hoge";
    this.age = age || 30;
}
var user1 = new User();
console.log(user1.name); // Hoge
console.log(user1.age); // 30

var user2 = new User("Boa", 25);
console.log(user2.name); // Boa
console.log(user2.age); // 25

配列切断

var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

Discussion (0)

pic
Editor guide