0
0

More than 1 year has passed since last update.

Code Warsでトレーニングしてみた

Last updated at Posted at 2022-11-10

Javascript編

toString()でバイナリに変換できる!

if文の複数条件で、||のOR演算子を使うとエラーになり、完全にハマった。
腹が減ったのでタイムアップとした。

Screen Shot 2022-11-10 at 18.24.46.png

自分の回答↓

function addBinary(a,b) {
  let sum = a + b;
  console.log(sum + "this is sum");

  sum = 2;
  console.log(sum + "Currently number");
  for(sum; sum !== 1;){
    
    console.log(sum + "for 1 statement is activating");
  }

律儀に10進数を2進数に変換する処理を作ろうとしてたが、10進数を 2進数に変換する関数があった。(そりゃあるよな...)

模範回答↓

function addBinary(a,b){
  return (a+b).toString(2)
}

メソッドチェーンはめっちゃ使える

なんかふわっとしか知らなかったメソッドチェーンだけど、案外使える。

良く使うjavascriptメソッド

注意点: 関数じゃないので下記のように変数に格納しないとエラーになる。

var 変数 = aaa.method();

toString()
10進数を2進数や16進数に変換できる

	var number = 3;
	var binaly = number.toString(2);
	// [resault] -> 11

数字をstring型に変換できる

	var number = 123;
	console.log(number);
	console.log("This data type is -> " + typeof number);
	// This data type is -> number.
	var str = number.toString();
	console.log(str);
	console.log("This data type is -> " + typeof str);
	// This data type is -> string.

reverse()
配列の要素を反転させる

var array = ["apple","banana","orange"];
	var reversedArray = array.reverse();
	// [result] -> "orange","banana","apple"

replace()
stringを置換する。

var str = "This is an sentense."
var replaceStr str.replace( /an/g , "a")
// [result] -> This is a sentense.

match()

sort()
配列の数値の並べ替えをしたい時に使える

	var numbers = [1,4,2,3,5];
	console.log(numbers);
	var sortedNumbers = numbers.sort(function compareNumbers(a,b){ return a - b });
	// 降順にしたい場合は、 return b - a
	console.log(sortedNumbers);
	// [1,2,3,4,5]

typeof
データ型を調べられる便利なやつ

	var str = "Hey";
	console.log("This data type is -> " + typeof str);
	// This data type is -> string

みたいな感じで良く使う
さらに、条件内にも使える!

    // データ型がstringだったら
    if(typeof value === "string")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0