Note:Array 常用幾種 Methods

  • Array.prototype.reverse()
    String.prototype.substr() method
    – String.prototype.charAt() method
  • Array.prototype.every()
  • Array.filter()
  • Array.fill()
  • Array.from()
  • Array.sort()

Array.prototype.reverse()

題目:
function reverseString(str) {
return str;
}
reverseString("hello");
//reverseString("hello") should become "olleh"
//reverseString("Howdy") should become "ydwoH"
//reverseString("Greetings from Earth") should return"htraE morf sgniteerG"

解法:先把字串拆解成單字(用 split(‘’)),再用 array.join(‘’) 組回 Array

function reverseString(str) {

Step 1. Use the split("") method to return a new array

var splitString = str.split(""); // var splitString = "hello".split(""); // ["h", "e", "l", "l", "o"]

Step 2. Use the reverse() method to reverse the new created array
var reverseArray = splitString.reverse(); // ["o", "l", "l", "e", "h"]

Step 3. Use the join("") method to join all elements of the array into a string
var joinArray = reverseArray.join("");  // "olleh"

Step 4. Return the reversed string
    return joinArray; // "olleh"
}

console.log(reverseString("hello")); //"olleh"

**更簡潔的解法:Chaining the three methods together

function reverseString(str) {
    return str.split("").reverse().join("");
}
console.log(reverseString("hello")); //"olleh"

二、Reverse a String With a Decrementing For Loop

function reverseString(str) {
Step 1. Create an empty string that will host the new created string
var newString = "";

Step 2. Create the FOR loop
for (var i = str.length - 1; i >= 0; i--) {
        newString += str[i]; // or newString = newString + str[i];

 }
Step 3. Return the reversed string
    return newString; // "olleh"
}

console.log(reverseString('hello')); // "olleh"

Loop 解析:

/* Here hello's length equals 5
For each iteration: i = str.length - 1 and newString = newString + str[i]First iteration:    i = 5 - 1 = 4,         
newString = "" + "o" = "o"

Second iteration:   i = 4 - 1 = 3,         
newString = "o" + "l" = "ol"

Third iteration:    i = 3 - 1 = 2,        
newString = "ol" + "l" = "oll"

Fourth iteration:   i = 2 - 1 = 1,         
newString = "oll" + "e" = "olle"

Fifth iteration:    i = 1 - 1 = 0,         
newString = "olle" + "h" = "olleh"

End of the FOR Loop*/

三、Reverse a String With Recursion

For this solution, we will use two methods:

String.prototype.substr() method
String.prototype.charAt() method

  • The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
var a =”hello”.substr(1);
console.log(a); // “ello”
  • The charAt() method returns the specified character from a string.
var a = "hello".charAt(0);
console.log(a); // "h"

解法:

function reverseString(str) {

if (str === "") 
// This is the terminal case that will end the recursion

return "";

else
return reverseString(str.substr(1)) + str.charAt(0);
}

console.log(reverseString("hello")); // "olleh";

更精簡的解法:

function reverseString(str) {

return (str === ‘’) ? ‘’ : reverseString(str.substr(1)) +

str.charAt(0);}

console.log(reverseString(“hello”)); "olleh";

解說:

/* 
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls

Each call: str === "?"        	                  reverseString(str.subst(1))+ str.charAt(0)

1st call – reverseString("Hello") will return reverseString("ello")           +"h"
2nd call – reverseString("ello") will return reverseString("llo")            + "e"
3rd call – reverseString("llo") will return reverseString("lo")             + "l"
4th call – reverseString("lo") will return reverseString("o")              + "l"
5th call – reverseString("o") will return reverseString("")               + "o"

Second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately

5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h" 
*/

Array.prototype.every()

→只會回傳 true or false;

基本寫法:arr.every(callback[, thisArg])
範例:
function isBigEnough(currentValue, index, array) {
return currentValue >= 10;
}

//currentValue(必要的)
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

Arrow function 寫法:
[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

另一個範例:

function isBelowThreshold(currentValue) {
 return currentValue < 40;
}
var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));// expected output: true

Array.filter()

常用在:要找到文字長度大於多少或是要過濾掉某些值時

基本寫法:var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
範例:
function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

另一個範例:

var words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array [“exuberant”, “destruction”, “present”]

Array.fill()

array.fill(要填入東西, 從第幾位, 到第幾位),須按照原本 Array 的長度

var array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

Array.from()

creates a new, shallow-copied Array instance from an array-like or iterable object.

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

Array.sort()

converting the elements into strings, then comparing their sequences of UTF-16 code units values.

var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

*Create an array with same element repeated multiple times

for loop 解法:

function fillArray(item, times) {

var arr = [];

for (var i = 0; i < times; i++) {

arr.push(item);

}
 return arr;

}

console.log(fillArray(30,2)); // [30,30]

conditional 解法:

function fillArray(value, len) {

if (len == 0) return [];

var a = [value];

while (a.length * 2 <= len) a = a.concat(a);

if (a.length < len) a = a.concat(a.slice(0, len — a.length));

return a;

}

console.log(fillArray(30, 2))
  • String.prototype.concat()
    把 string 串在ㄧ起
var str1 = ‘Hello’;
var str2 = ‘World’;

console.log(str1.concat(‘ ‘, str2));
// expected output: “Hello World”

console.log(str2.concat(‘, ‘, str1));
// expected output: “World, Hello”
  • String.prototype.slice()
    把 string 從每一個單位開始切出
var str = ‘How are You’;

console.log(str.slice(10));
//”u”

console.log(str.slice(4, 19));
//”are You”