We all want to be famous people, and the moment we want to be something we are no longer free.
--Jiddu Krishnamurti
In JavaScript, arrays are just objects, it make arrays can access methods, like other objects—methods that will make our lives a lot easier, here we will talk some essential ones.
push
let fruits = ["apple", "orange"]
let count = fruits.push("banana") // "apple", "orange", "banana"
console.log(count) // 3
pop
const last = fruits.pop() // "apple", "orange"
console.log(last) // "banana"
unshift
count = fruits.unshift("banana") // "banana", "apple", "orange"
console.log(count) // 3
shift
const first = fruits.shift()
console.log(first) // banana
splice
fruits.splice(1, 0, "watermelon") // "apple", "watermelon", "orange"
fruits.splice(2) // "apple", "watermelon"
map
The map method creates a new array with the results of calling a callback on every element.
fruits = fruits.map(fruit => fruit.toUpperCase()) // "APPLE", "WATERMELON"
fruits.unshift(fruits.pop()) // "WATERMELON", "APPLE"
sort
fruits.sort((a, b) => {
if (a < b) return -1
if(a > b) return 1
return 0
})
fruits.push(fruits.shift()) // "WATERMELON", "APPLE"
find
let myFruit = fruits.find(fruit => fruit.toLowerCase().includes("water"))
console.log(myFruit) // "WATERMELON"
filter
let myFruits = fruits.filter(fruit => fruit.toLowerCase().includes("melon"))
console.log(myFruits) // ["WATERMELON"]
reduce
The reduce method aggregates all items in an array into a single value.
let reduced = fruits.reduce((tenet, fruit) => tenet += fruit + (fruit != fruits[fruits.length-1] ? " AND " : ""), "")
console.log(reduced) // APPLE AND WATERMELON
every/some
The every and some methods determine whether all or some array items satisfy a certain criterion. We can use it to a replacement of forEach function, the benefit is that we can opt to stop the iteration early to improve efficiency.
fruits.some(fruit => {
console.log(fruit)
if (fruit.toLowerCase().includes("melon")) {
console.log(fruit + " is melon")
return true
}
return false
})
// WATERMELON
// WATERMELON is melon
网友评论