DEV Community 👩‍💻👨‍💻

D
D

Posted on

ちょっと便利なJavaScript技

!!で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
Enter fullscreen mode Exit fullscreen mode

+文字列を数値に変換

function toNumber(strNumber){
  return +strNumber;
}

console.log(toNumber("1234")); // 1234
console.log(toNumber("ABC")); //NaN
Enter fullscreen mode Exit fullscreen mode

&& 条件式

if (connected){
  login();
}

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

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

||でデフォルト値設定

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
Enter fullscreen mode Exit fullscreen mode

配列切断

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]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.