美文网首页
Useful Methods of JavaScript Arr

Useful Methods of JavaScript Arr

作者: 7dbe8fdb929f | 来源:发表于2020-10-23 16:24 被阅读0次

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

相关文章

网友评论

      本文标题:Useful Methods of JavaScript Arr

      本文链接:https://www.haomeiwen.com/subject/sesvmktx.html