Javascript Array 陣列 8種方法

  1. 8 Must-Know JavaScript Array Methods
    1. 01 .forEach()
    2. 02 .map()
    3. 03 .filter()
    4. 04 .concat()
    5. 05 .find()
    6. 06 .push()
    7. 07 .pop()
    8. 08 .includes()

8 Must-Know JavaScript Array Methods

01 .forEach()

Executes a provided function once for each array element.

// .forEach()
const emojis = ['football','run','pizza']

emojis.forEach(emoji => {
    console.log(`I love ${emoji}`) //注意 `` 這個符號
})

02 .map()

Creates a new array populated with the results of calling a provided function on every element.

// .map()
const emojis = ['football','run','pizza']

const result = emojis.map(emoji => {
    return emoji + emoji 
})

console.log(result)

//result : [ 'footballfootball', 'runrun', 'pizzapizza' ]

03 .filter()

Creates a new array with all elements that pass the test implemented by the provided function.

// .filter()
const emojis = ['football','run','pizza','basketball']

const pet = emojis.filter(emoji => {
    return emoji == 'football' || emoji == 'run'
})

console.log(pet)
//result : [ 'football', 'run' ]

04 .concat()

Creates a new array by merging two or more arrays.

// .concat()
const fruits = ['apple','banana']
const vegetables = ['carrot','tomato']

const result = fruits.concat(vegetables)

console.log(result)
//result : [ 'apple', 'banana', 'carrot', 'tomato' ]

05 .find()

Returns the value of the first array element that satisfies the provided test function, or undefined

//.find()
const emojis = ['sun','moon','pizza','basketball']

const moon = emojis.find(emoji => {
    return emoji == 'moon'
})

console.log(moon)
//result : moon

06 .push()

Adds the specified elements to the end of an array.

//.push()
const emojis = ['donut','cake','cookies']

emojis.push('ice cream')

console.log(emojis)
//result : [ 'donut', 'cake', 'cookies', 'ice cream' ]

07 .pop()

Removes the last element from an array and returns it.

//.pop()
const emojis = ['donut','cake','cookies']
const lastEmoji = emojis.pop()

console.log(lastEmoji)
console.log(emojis)
/*result : 
cookies
[ 'donut', 'cake' ]
*/

08 .includes()

Determines whether an array includes a certain value or not.

//.includes()
const emojis = ['donut','cake','cookies']

const hasDonut = emojis.includes('donut')
console.log(hasDonut)

const hasIceCream = emojis.includes('ice cream')
console.log(hasIceCream)

/*#result : 
true
false
*/

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 kimfei2014@gmail.com
github