javascript中数组的常用API及Vue中如何调用的实例

  1. push() : 该方法用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['apple', 'banana'];
fruits.push('orange', 'grape');
console.log(fruits);
// 输出:['apple', 'banana', 'orange', 'grape']
  1. pop() : 该方法用于从数组的末尾移除最后一个元素,并返回被移除的元素。
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(removedFruit);
// 输出:'orange'
console.log(fruits);
// 输出:['apple', 'banana']
  1. shift() : 该方法用于从数组的开头移除第一个元素,并返回被移除的元素。
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit);
// 输出:'apple'
console.log(fruits);
// 输出:['banana', 'orange']
  1. unshift() : 该方法用于向数组的开头添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['banana', 'orange'];
fruits.unshift('apple', 'grape');
console.log(fruits);
// 输出:['apple', 'grape', 'banana', 'orange']
  1. splice() : 该方法用于从数组中添加或删除元素,并返回被删除的元素组成的数组。
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'kiwi', 'melon');
console.log(removedFruits);
// 输出:['banana', 'orange']
console.log(fruits);
// 输出:['apple', 'kiwi', 'melon', 'grape']
  1. sort() : 该方法用于对数组进行原地排序,默认按照字符串的Unicode编码进行排序
const numbers = [3, 1, 5, 2, 4];
numbers.sort();
console.log(numbers);
// 输出:[1, 2, 3, 4, 5]
  1. reverse() : 该方法用于原地反转数组中的元素顺序。
const fruits = ['apple', 'banana', 'orange'];
fruits.reverse();
console.log(fruits);
// 输出:['orange', 'banana', 'apple']

下面是Vue中的里一个调用,因为Vue对这些基础API进行了封装,封装的对象都是会对原数组进行改动的。

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
    <script src="../../vue.js/vue.js">script>
  head>
  <body>
    <div id="app">
      <div v-for="item in list">{{item.name}}-{{item.age}}div>
      <button @click="change">改变button>
    div>
    <script>
      Vue.config.productionTip=false
      new Vue({
      el: '#app',
      data: {
        list:[{
          name:"张三",age:27
        }]
      },
      methods: {
        change(){
          this.list.splice(0,1,{name:"李四",age:18})
        }
      },
      });

    script>
  body>
html>

你可能感兴趣的:(前端,vue.js,javascript,前端)