-
Iteration methods:會每一個element都給他see一次,every()、filter()、forEach()、map()、some()
-
Accessor methods:不會更動陣列本身,只是呈現你想呈現的,lastIndexOf()、indexOf()
-
Mutator methods:push() pop() unshift() shift()
fill it,參考
new Array(3).fill(null)
// [ null, null, null ]
new Array(5+1).join('0').split('')
// ["0", "0", "0", "0", "0"]
new Array(5+1).join('0').split('').map(parseFloat)
// [0, 0, 0, 0, 0]
Array.from(Array(3), () => 0)
// [0, 0, 0]
Array.from(Array(10), (d, i) => d)
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],透過index
copy,參考
// Highest performance for deep copying literal values
arr2 = arr1.slice();
// Any of these techniques will deep copy literal values as well,
// but with lower performance.
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = $.extend(true, [], arr1); // jQuery.js needed
arr2 = _.extend(arr1); // Underscore.js needed
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = copy(arr1); // Custom-function needed - as provided above
arr2 = [].concat(arr1)
arr2 = [...arr1]
Array.from('foo')
// ["f", "o", "o"]
return true
Array.isArray([])
Array.isArray([1])
Array.isArray(new Array())
特別一點:Array.prototype itself is an array:
Array.isArray(Array.prototype)
return false
Array.isArray()
Array.isArray({})
Array.isArray(null)
Array.isArray(undefined)
Array.isArray(17);
Array.isArray('Array')
Array.isArray(true)
Array.isArray(false)
Array.isArray({ __proto__: Array.prototype })
const num1 = [[1]]
const num2 = [2, [3]]
const nums = num1.concat(num2)
console.log(nums) //[[1], 2, [3]]
num1[0].push([4])
console.log(nums) //[ [ 1, [ 4 ] ], 2, [ 3 ] ]
[1, 2, 3, 4, 5].copyWithin(-2);
// [1, 2, 3, 1, 2]
[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]
[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}
const arr = ['a', 'b', 'c']
const eArr = arr.entries()
console.log(eArr.next().value) // [0, 'a']
console.log(eArr.next().value) // [1, 'b']
console.log(eArr.next().value) // [2, 'c']
// 若用for… of迴圈
const arr = ['a', 'b', 'c']
const eArr = arr.entries()
for (let e of eArr) {
console.log(e)
}
function isBigEnough(element, index, array) {
return element >= 10
}
[12, 5, 8, 130, 44].every(isBigEnough) // false
[12, 54, 18, 130, 44].every(isBigEnough) // true
[1, 2, 3].fill(4) // [4, 4, 4]
[1, 2, 3].fill(4, 1) // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2) // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1) // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2) // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN) // [1, 2, 3]
Array(3).fill(4) // [4, 4, 4]
[].fill.call({ length: 3 }, 4) // {0: 4, 1: 4, 2: 4, length: 3}
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' },
{ id: undefined },
{ id: 24 },
]
let invalidEntries = 0
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj)
}
function filterByID(item) {
if (isNumber(item.id)) return true
invalidEntries++
return false
}
const arrByID = arr.filter(filterByID)
console.log('Filtered Array\n', arrByID)
console.log('Number of Invalid Entries = ', invalidEntries)
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries'
}
console.log(inventory.find(findCherries))
// { name: 'cherries', quantity: 5 }
function isPrime(element, index, array) {
let start = 2
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false
}
return element > 1
}
console.log([4, 6, 8, 12].find(isPrime)) // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)) // 5
缺點是只會回傳第一個符合的,find()也是
function isPrime(element, index, array) {
let start = 2
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false
}
return element > 1
}
console.log([4, 6, 8, 12].findIndex(isPrime)) // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)) // 2
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element)
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements)
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
const arr = ['a', 'b', 'c'];
arr.includes('c', 3) //false
arr.includes('c', 100) // false
const indices = []
const array = ['a', 'b', 'a', 'c', 'a', 'd']
const element = 'a'
let idx = array.indexOf(element)
while (idx !== -1) {
indices.push(idx)
idx = array.indexOf(element, idx + 1)
}
console.log(indices)
// [0, 2, 4]
const a = ['Wind', 'Rain', 'Fire']
a.join(); // 'Wind,Rain,Fire'
a.join(', ') // 'Wind, Rain, Fire'
a.join(' + ') // 'Wind + Rain + Fire'
a.join(''); // 'WindRainFire
注意,object.keys()可忽略沒有的東西,但arr.keys()不行
var arr = ['a', , 'c']
var sparseKeys = Object.keys(arr)
var denseKeys = [...arr.keys()]
console.log(sparseKeys) // ['0', '2']
console.log(denseKeys) // [0, 1, 2]
// , ,
arr[1] == null //true
arr[1] == undefined //true
arr[1] === undefined //true
arr[1] === null //false
arr[1] === '' //false
// ,'',
arr[1] == null //false
arr[1] == undefined //false
arr[1] === undefined //false
arr[1] === null //false
arr[1] === '' //true
倒著找
cosnst numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2) // 3
numbers.lastIndexOf(7) // -1
numbers.lastIndexOf(2, 3) // 3
numbers.lastIndexOf(2, 2) // 0
numbers.lastIndexOf(2, -2) // 0
numbers.lastIndexOf(2, -1) // 3
const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
]
const reformattedArray = kvArray.map((obj) => {
const rObj = {}
rObj[obj.key] = obj.value
return rObj
})
const map = Array.prototype.map
const a = map.call('Hello World', x => {
return x.codePointAt(0)
})
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
const numbers = [1, 4, 9];
const doubles = numbers.map((num) => num * 2)
// doubles is now [2, 8, 18]
// numbers is still [1, 4, 9]
doubles
const myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
const popped = myFish.pop()
console.log(myFish) // ['angel', 'clown', 'mandarin' ]
console.log(popped) // 'sturgeon'
回傳數量length
const sports = ['soccer', 'baseball'];
const total = sports.push('football', 'swimming');
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
const total = [ 1, 2, 3, 4 ].reduce(
( acc, cur ) => acc + 2 * cur);
// 19
倒過來reduce
const total = [ 1, 2, 3, 4 ].reduceRight(
( acc, cur ) => acc + 2*cur);
// 16
const a = ['one', 'two', 'three'];
const b = a.slice()
const reversed = a.reverse();
console.log(a) // ['three', 'two', 'one']
console.log(reversed) // ['three', 'two', 'one']
console.log(b) // ['one', 'two', 'three']
const words = ['one', 'two', 'three', 'four']
words.forEach((word) => {
console.log(word)
if (word === 'two') words.shift()
})
// one
// two
// four
words
// [ 'two', 'three', 'four' ]
const myFish = ['angel', 'clown', 'mandarin', 'surgeon']
const shifted = myFish.shift()
console.log(myFish) // ['clown', 'mandarin', 'surgeon']
console.log(shifted) // angel
const fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
const citrus = fruits.slice(1, 3)
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
function sortArgs(...args) {
args = [].slice.call(args)
console.log(args.length)
console.log(args.sort())
}
sortArgs("c", "d", /*x*/9, "x")
// 4
// [ 9, 'c', 'd', 'x' ]
function isBiggerThan10(element, index, array) {
return element > 10
}
[2, 5, 8, 1, 4].some(isBiggerThan10) // false
[12, 5, 8, 1, 4].some(isBiggerThan10) // true
const fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
return arr.some(arrVal => val === arrVal);
}
checkAvailability(fruits, 'kela'); // false
checkAvailability(fruits, 'banana'); // true
const mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200]
function compareNumbers(a, b) {
return a - b
}
//下面這個compare走相反路線
function compare(a, b) {
if (a < b) return 1; //1代表往後走
if (a > b) return -1
// a must be equal to b
return 0;
}
console.log('Sorted:', stringArray.sort());
stringArray.sort(compare) === stringArray.sort().reverse()
// true
mixedNumericArray.sort()
// [ 1, 200, 40, 5, '700', '80', '9' ]
mixedNumericArray.sort(compare)
// [ '9', '80', '700', 200, 40, 5, 1 ]
mixedNumericArray.sort(compareNumbers)
// [ 1, 5, '9', 40, '80', 200, '700' ]
const myFish = ['angel', 'clown', 'trumpet', 'sturgeon']
const removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue')
// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]
const arr = [1, 2];
arr.unshift(0); // 3
// arr is [0, 1, 2]
arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]
arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]
const arr = ['a', , 'c'];
const sparseKeys = Object.values(arr); (ok)
const denseKeys = [...arr.values()];
console.log(sparseKeys); // ['a', 'c']
console.log(denseKeys) 跑不出來!
- Array.prototype.toLocaleString()
- Array.prototype.toSource()
- Array.prototype.toString()