function reverseString(str) {
return str.split('').reverse().join('');
}
Factorialize a Number
function factorialize(num) {
var temp=1;
for(i=num; i>0; i--){
temp=temp*i;
}
return temp;
}
factorialize(5);
官方解答
用遞歸,函數自己呼叫自己
function factorialize(num) {
if (num === 0) { return 1; }
return num * factorialize(num-1);
}
factorialize(5);
Check for Palindromes
官方解答有三種版本,我的解法偏向第二種
function palindrome(str) {
// Good luck!
// 切換成小寫,排除非字母符號,將字串轉成矩陣
regular = /[A-Za-z0-9]/g;
var lowerStr = str.toLowerCase(); // 轉成小寫
var matchStr = lowerStr.match(regular);
// 比較 i, matcherStr.length -i-1 的字母是否相同
for (i=0; i<matchStr.length/2; i++){
if (matchStr[i]!=matchStr[matchStr.length-1-i]){
return false;
}
}
return true;
}
palindrome("0_0 (: /-\ :) 0-0");
Find the Longest Word in a String
官方解答的第二三種作法,對我來說有點不直覺
二用了reduce()和math.max(),三用了recursiveness遞歸
function findLongestWord(str) {
var strArray = str.split(" ");
var strLength=0;
for(i=0; i<strArray.length; i++){
if(strArray[i].length>strLength){
strLength = strArray[i].length;
console.log("i="+i);
console.log("strLength="+strLength);
}
}
return strLength;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
我的第二種,用max
function findLongestWord(str) {
// 请把你的代码写在这里
strArray = str.split(" ");
numArray = [];
for(i=0; i<strArray.length; i++){
numArray[i]=strArray[i].length;
}
biggestLength = Math.max(...numArray);
return biggestLength;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
var strEnd = str.substring(str.length - target.length, str.length);
return strEnd == target;
}
confirmEnding("Bastian", "n");
官方解答
function confirmEnding(str, target) {
return str.substr(-target.length) === target;
}
Repeat a string repeat a string
push 進陣列再 join 成字串的作法好蠢阿阿阿阿阿
有人說用 while 比較省時間
concat
repeat
遞迴
function repeatStringNumTimes(str, num) {
// repeat after me
var timeStr=[];
for(i=0; i<num; i++){
timesStr=timeStr.push(str);
}
return timeStr.join("");
}
repeatStringNumTimes("abc", 3);
Truncate a string
自己想的方法
function truncateString(str, num) {
// Clear out that junk in your trunk
var dotstr;
if(num>=str.length){
dotstr = str;
}
else if(num<3){
dotstr = str.slice(0,num)+"...";
}
else if(num<str.length){
dotstr = str.slice(0,num-3)+"...";
}
console.log(dotstr);
return dotstr;
}
truncateString("A-tisket a-tasket A green and yellow basket", 11);
官方的進階解答
function truncateString(str, num) {
if (str.length <= num) {
return str;
} else {
return str.slice(0, num > 3 ? num - 3 : num) + '...';
}
function mutation(arr) {
// 请把你的代码写在这里
one = arr[0].toLowerCase();
two = arr[1].toLowerCase();
for(i=0; i<two.length; i++){
if(one.indexOf(two[i]) === -1 ){
return false;
}
}
return true;
}
a = mutation(["hello", "he"]);
console.log(a)
先練習 every 的用法
var arr = [true, false, true];
function test(arr){
return arr.every(function(val){
return val === true;
})
}
console.log(test(arr)); // false
自己的寫法
function mutation(arr) {
// 请把你的代码写在这里
// 先定義變數,把arr[0]轉成小寫,把arr[1]轉成小寫再分割字母
var FirStr = arr[0].toLowerCase();
var SecArr = arr[1].toLowerCase().split("");
// SecArr 的字母,在FirStr中都有位置(indexOf回傳不是-1)?
result = SecArr.every( (val) => FirStr.indexOf(val) !== -1 );
//回傳結果
console.log(result);
return result;
}
mutation(["hello", "h"]);
Falsy Bouncer
去除 falsy 值,也就是 boolean 值為 false 的值
function bouncer(arr) {
// Don't show a false ID to this bouncer.
return arr.filter( (val) => Boolean(val) != false );
}
bouncer([7, "ate", "", false, 9]);
留言串看到的解法
function bouncer(arr) {
var a = [];
arr.forEach(function(el){
if(el){
a.push(el);}});
return a;}
列舉式的寫法
function badValues(val){
return val !== false && val !== null && val !== 0 && val !== "" && val !== undefined && !Number.isNaN(val);
}
function bouncer(arr) {
return arr.filter(badValues);
}
bouncer([1, null, NaN, 2, undefined]);
Seek and Destroy
從矩陣中移除後面參數出現的東西
參數物件,第一次聽到這個東西
function destroyer(arr) {
// Remove all the values
// 先拿到參數矩陣,再另存參數一矩陣
var args = Array.from(arguments);
var arr0 = args.shift(); //arr0等於參數一,args等於其他的參數
// 排除arr0 中含有 agrs 的內容
// callback 函數有三個參數,當前值,目錄,與要篩選的矩陣
// 如果args[i]==val,回傳 false,代表從arr0篩除
return arr0.filter(function(val, index, arr0){
var result = true;
// 如果有一個
for(i=0; i<args.length; i++){
if (args[i]===val){
result = false;
}
}
return result;
});
}
a = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(a)
其他解法
var args = Array.prototype.slice.call(arguments, 1);
return arr.filter(function(val){ return args.every(x => x !== val); });
其他解法
function destroyer(arr) {
var filterList = [];
for (var i = 1; i < arguments.length; i++) {
filterList.push(arguments[i]);
}
return arr.filter(function(val) {
return filterList.indexOf(val) < 0;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
其他解法
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments, destroyer.length);
return arr.reduce((acc, item) => {
if (!args.includes(item)) {
acc.push(item);
}
return acc;
}, []);
官方解法一
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < args.length; j++) {
if (arr[i] === args[j]) {
delete arr[i];
}
}
}
return arr.filter(Boolean);
官方解法二
function destroyer(arr) {
var args = Array.from(arguments).slice(1);
return arr.filter(function(val) {
return !args.includes(val);
});
}
Where do I belong
我的解法
一開始忘記 sort 的特性,做了許多白工
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr.sort((a,b)=>a-b);
return arr.indexOf(num);
}
getIndexToIns([2, 5, 10], 15);
官方的中等作法
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr.sort((curr, next) => curr > next)
.findIndex((currNum)=> num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
getIndexToIns([40, 60], 500);
官方的進階作法
function getIndexToIns(arr, num) {
return arr.concat(num).sort((a,b) => a-b).indexOf(num);
}
getIndexToIns([1,3,4],2);
Caesars Cipher
function rot13(str) { // LBH QVQ VG!
var result="";
var zAt = "Z".charCodeAt(0);
var aAt = "A".charCodeAt(0);
for(i=0; i<str.length; i++){
if(/\W/.exec(str[i])){
result = result + str[i];
}
else if( (zAt - str.charCodeAt(i)) < 13){
result = result + String.fromCharCode(str.charCodeAt(i)-13);
}
else{
result = result + String.fromCharCode(str.charCodeAt(i)+13);
}
}
console.log(result);
return result;
}
// Change the inputs below to test
rot13("SERR CVMMN!");
function rot13(str) {
// Split str into a character array
return str.split('')
// Iterate over each character in the array
.map.call(str, function(char) {
// Convert char to a character code
x = char.charCodeAt(0);
// Checks if character lies between A-Z
if (x < 65 || x > 90) {
return String.fromCharCode(x); // Return un-converted character
}
//N = ASCII 78, if the character code is less than 78, shift forward 13 places
else if (x < 78) {
return String.fromCharCode(x + 13);
}
// Otherwise shift the character 13 places backward
return String.fromCharCode(x - 13);
}).join(''); // Rejoin the array into a string
}
官方解法二
fn.apply(something, array) 可以把矩陣的內容當作參數個別傳入
regular.test() 傳回 boolean
// Solution with Regular expression and Array of ASCII character codes
function rot13(str) {
var rotCharArray = [];
var regEx = /[A-Z]/ ;
str = str.split("");
for (var x in str) {
if (regEx.test(str[x])) {
// A more general approach
// possible because of modular arithmetic
// and cyclic nature of rot13 transform
rotCharArray.push((str[x].charCodeAt() - 65 + 13) % 26 + 65);
} else {
rotCharArray.push(str[x].charCodeAt());
}
}
str = String.fromCharCode.apply(String, rotCharArray);
return str;
}
// Change the inputs below to test
rot13("LBH QVQ VG!");
第三種解法
$0 代表正則表達式篩出來的內容,$1 代表內容的第一個被篩出來的部份
function rot13(str) { // LBH QVQ VG!
return str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}