DEV Community

D
D

Posted on

3 2

ちょっと便利な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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay