Note:簡化 conditional statement 寫法 & Array 與 String 常用方法

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B" // -1
  • "A" == "B" // 0
  • "A" > "B" // 1
function cal(A,B)
{ 
 return 
(A<B?-1:
(A>B?1:
 0)
); 
}

console.log(cal(3, 3)); // 0
console.log(cal(1, 3)); // -1
console.log(cal(5, 3)); // 1

Array 與 String 常用方法

*String.prototype.split() → String into Array

題目:Create a function that takes a string and returns a string with its letters in alphabetical order.
AlphabetSoup("hello") ➞ "ehllo"
AlphabetSoup("edabit") ➞ "abdeit"
AlphabetSoup("hacker") ➞ "acehkr"
AlphabetSoup("geek") ➞ "eegk"
AlphabetSoup("javascript") ➞ "aacijprstv"

解法:

function AlphabetSoup(str) {
var a = str.split(‘’);
var b = a.sort();
return (b.join(‘’)); 
}

String.prototype.split()

1.Sentence
(1)找到句子中的單字
var str = ‘The quick brown fox jumps over the lazy dog.’;
var words = str.split(‘ ‘);
console.log(words[3]);

// expected output: “fox”
(2)找到句子中的字母
var chars = str.split('');
console.log(chars[8]);

// expected output: "k"
(3)把句字變成 Array
var strCopy = str.split();
console.log(strCopy);

// expected output: Array ["The quick brown fox jumps over the lazy dog."]

2.Word
(1)把單字變成 array
var str = ‘fox’;
var words = str.split(‘ ‘); // 或者 var words = str.split();
console.log(words);

// expected output: ["fox"]
(2)把單字變成 array,裡面切成字母
var str = ‘fox’;
var chars = str.split('');
console.log(chars);

// Array ["f", "o", "x"]

*Array.join() → Array into String

var elements = [‘Fire’, ‘Wind’, ‘Rain’];
console.log(elements.join());

// expected output: “Fire,Wind,Rain”
console.log(elements.join(‘’));

// expected output: “FireWindRain”
console.log(elements.join(‘-’));

// expected output: “Fire-Wind-Rain”

單字也可以用 join:

var elements = [‘f’,’o’,’x’];

console.log(elements.join());

// expected output: "f,o,x"

console.log(elements.join(‘’));

// expected output: "fox"

console.log(elements.join(‘-’));

// expected output: "f-o-x"