JavaScript 进阶(未完待续)

集合

Array

  1. 2种创建数组的方式

    var fruits = [] ;
    var friuits = new Array();

  2. 遍历

    fruits.forEach(function (item, index, array){
    console.log(item, index);
    });
    // Apple 0
    // Banana 1

  3. 基本操作

操作 代码 返回值
添加元素到数组的末尾 fruits.push('Orange') 数组长度
添加元素到数组的头部 fruits.unshift('Strawberry') 数组长度
删除头部元素 fruits.shift(); 头部元素
删除尾部元素 fruits.pop(); 尾部元素
找出某个元素在数组中的索引 fruits.indexOf('Banana'); 下标
通过索引删除某个元素 fruits.splice(index, 1); 被删除的元素
复制数组 var shallowCopy = fruits.slice(0,length); 返回指定范围内元素组成的新数组
生成数组 Array.from() Array.from() 方法从一个类似数组或可迭代对象中创建一个新的数组实例。
  1. 根据索引删除元素的例子

    /* splice(start: number, deleteCount: number, ...items: T[]): T[]; */

    var fruits = ["apple","b","c","d"] ;
    console.log("array is : ");
    fruits.forEach(function (item, index, array){
    console.log(item, index);
    });
    var index = fruits.indexOf("b");
    fruits.splice(index,1);
    console.log("array is : ");
    fruits.forEach(function (item, index, array){
    console.log(item, index);
    });

  2. Array.from()使用例子

    var fruits = ["apple","b","c","d"] ;
    var f = Array.from(fruits);
    f.forEach(function (item, index, array){
    console.log(item, index);
    });
    //apple 0
    //b 1
    //c 2
    //d 3

    var f = Array.from("hello");
    f.forEach(function (item, index, array){
    console.log(item, index);
    });
    //h
    //e
    //l
    //l
    //o

    Array.from()还可以用于Set,Map

Set

Map

猜你喜欢

转载自www.cnblogs.com/chenjingquan/p/9158682.html
今日推荐