您当前的位置: 首页 > 

知其黑、受其白

暂无认证

  • 0浏览

    0关注

    1250博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JS基础 数组类型

知其黑、受其白 发布时间:2022-01-26 18:36:11 ,浏览量:0

阅读目录
  • 声明数组
    • 创建数组
    • Array.of
    • 类型检测
  • 类型转换
    • 字符串转数组
    • Array.from 将类数组转换为数组
  • 展开语法
    • 数组合并
    • 函数参数
    • 节点转换
  • 解构赋值
    • 基本使用
    • 严格模式
    • 简洁定义
    • 默认值
    • 函数参数
  • 管理数组元素
    • 基本使用
    • 扩展语法
    • push 压入元素
    • pop 从末尾弹出元素
    • shift 从数组前面取出一个元素
    • unshift 从数组前面添加元素
    • fill 填充数组元素
    • slice 从数组中截取部分元素组合成新数组
    • splice 添加、删除、替换数组中的元素
    • 清空数组
  • 合并拆分
    • join 数组连接成字符串
    • split 将字符串分割成数组
    • concat 连接两个或多个数组
    • copyWithin 从数组中复制一部分到同数组中的另外位置
  • 数组查找元素
    • indexOf 从前向后查找元素出现的位置
    • lastIndexOf 从后向前查找元素出现的位置
    • includes 查找字符串返回值是布尔类型
    • find 方法找到后会把值返回出来
    • findIndex 返回索引值
    • find 原理
  • 数组排序
    • reverse 反转数组顺序
    • sort 每次使用两个值进行比较
    • 排序原理
  • 循环遍历
    • for 根据数组长度循环来遍历数组
    • forEach 使函数作用在每个数组元素上,但是没有返回值。
    • for/in 遍历时的 key 值为数组的索引
    • for/of 每次循环取其中的值而不是索引
  • 迭代器方法
    • keys 通过迭代对象获取索引
    • values 通过迭代对象获取值
    • entries 返回数组所有键值对
  • 扩展方法
    • every 用于递归的检测元素
    • some 递归的检测元素
    • filter 滤数据中元素
    • map 映射在数组所有元素上应用函数
    • reduce 迭代数组的所有元素
      • 使用 reduce 实现数组去重
      • 示例
      • 统计元素出现的次数
      • 取数组中的最大值
      • 取价格最高的商品
      • 计算购物车中的商品总价
      • 获取价格超过1万的商品名称
  • 动画案例

声明数组

数组是多个变量值的集合,数组是Array 对象的实例,所以可以像对象一样调用方法。

创建数组

使用对象方式创建数组

console.log(new Array(1, 'wgchen', 'willem')); // [1, 'wgchen', 'willem']

使用字面量创建是推荐的简单作法

const array = ["wgchen", "willem"];

多维数组定义

const array = [["wgchen"], ["willem"]];
console.log(array[1][0]); // willem

数组是引用类型可以使用 const 声明并修改它的值

const array = ["wgchen", "willem"];
array.push("ycc");
console.log(array); // ['wgchen', 'willem', 'ycc']

使用原型的 length 属性可以获取数组元素数量

let hd = ["wgchen", "willem"];
console.log(hd.length); //2

数组可以设置任何值,下面是使用索引添加数组

let hd = ["wgchen"];
hd[1] = "willem";

console.log(hd) // ['wgchen', 'willem']

下面直接设置 3 号数组,会将 1/2 索引的数组定义为空值

let hd = ["wgchen"];
hd[3] = "willem";
console.log(hd.length); //4
console.log(hd); // ['wgchen', 空 ×2, 'willem']

声明多个空元素的数组

let hd = new Array(3);

console.log(hd.length);
console.log(hd);
Array.of

使用 Array.of 与 new Array 不同是设置一个参数时不会创建空元素数组

let hd = Array.of(3);
console.log(hd); //[3]

hd = Array.of(1, 2, 3);
console.log(hd); //[1, 2, 3]
类型检测

检测变量是否为数组类型

console.log(Array.isArray([1, "wgchen", "willem"])); //true
console.log(Array.isArray(9)); //false
类型转换

可以将数组转换为字符串也可以将其他类型转换为数组。

字符串转数组

大部分数据类型都可以使用.toString() 函数转换为字符串。

console.log(([1, 2, 3]).toString()); // 1,2,3

也可以使用函数 String 转换为字符串。

console.log(String([1, 2, 3]));

或使用 join 连接为字符串

console.log([1, 2, 3].join("-"));//1-2-3
Array.from 将类数组转换为数组

使用 Array.from 可将类数组转换为数组,类数组指包含 length 属性或可迭代的对象。

第一个参数为要转换的数据 第二个参数为类似于map 函数的回调方法

let str = 'wgcehn';
console.log(Array.from(str)); // ['w', 'g', 'c', 'e', 'h', 'n']

为对象设置 length 属性后也可以转换为数组,但要下标为数值或数值字符串

let user = {
  0: 'wgchen',
  '1': 18,
  length: 2
};
console.log(Array.from(user)); // ["wgchen", 18]

DOM元素转换为数组后来使用数组函数, 第二个参数类似于map 函数的方法,可对数组元素执行函数处理。


    button
    button



    let btns = document.querySelectorAll('button');
    console.log(btns); //包含length属性
    
    Array.from(btns, (item) => {
        item.style.background = 'red';
    });

在这里插入图片描述

展开语法

使用展开语法将 NodeList 转换为数组操作


    .hide {
      display: none;
    }



  wgchen
  willem



  let divs = document.querySelectorAll("div");
  
  [...divs].map(function(div) {
    div.addEventListener("click", function() {
      this.classList.toggle("hide");
    });
  });

在这里插入图片描述

数组合并

使用展开语法来合并数组相比 concat 要更简单,使用 ... 可将数组展开为多个值。

let a = [1, 2, 3];
let b = ['a', 'wgchen', ...a];
console.log(b); // ['a', 'wgchen', 1, 2, 3]
函数参数

使用展示语法可以替代 arguments 来接收任意数量的参数

function hd(...args) {
  console.log(args);
}

hd(1, 2, 3, "wgchen"); // [1, 2, 3, 'wgchen']

也可以用于接收部分参数

function hd(site, ...args) {
  console.log(site, args); // 
}

hd("wgchen", 1, 2, 3);

在这里插入图片描述

节点转换

可以将DOM节点转为数组,下面例子不可以使用 filter 因为是节点列表


    button
    button



    let btns = document.querySelectorAll('button');
    btns.map((item) => {
        console.log(item); //TypeError: btns.filter is not a function
    })

使用展开语法后就可以使用数据方法



    .hide {
      display: none;
    }



    button
    button



    let divs = document.querySelectorAll("div");
    [...divs].map(function (div) {
        div.addEventListener("click", function () {
            this.classList.toggle("hide");
        });
    });

学习后面章节后也可以使用原型处理


    button
    button



    let btns = document.querySelectorAll('button');
    Array.prototype.map.call(btns, (item) => {
        item.style.background = 'red';
    });

在这里插入图片描述

解构赋值

解构是一种更简洁的赋值特性,可以理解为分解一个数据的结构

建设使用 var/let/const 声明

基本使用

下面是基本使用语法

//数组使用
let [name, url] = ['wgchen', 'ycc'];
console.log(name);   // wgchen 

解构赋值数组

function hd() {
    return ['wgchen', 'willem'];
}

let [a, b] = hd();
console.log(a); // wgchen

剩余解构指用一个变量来接收剩余参数

let [a, ...b] = ['wgchen', 'ycc', 'willem'];
console.log(b); // ['ycc', 'willem']

如果变量已经初始化过,就要使用 ()定义赋值表达式,严格模式会报错所以不建议使用。

let web = "wgchen";
[web, url] = ["wgchen", "ycc"];

console.log(web); // wgchen

字符串解构

"use strict";
const [...a] = "wgchen";

console.log(a); // ['w', 'g', 'c', 'h', 'e', 'n']
严格模式

非严格模式可以不使用声明指令,严格模式下必须使用声明。 所以建议使用 let 等声明。

"use strict";

[web, url] = ["wgchen", "ycc"];
console.log(web); // Uncaught ReferenceError: web is not defined
简洁定义

只赋值部分变量

let [,url]=['ycc','wgchen'];
console.log(url); // wgchen

使用展开语法获取多个值

let [name, ...arr] = ['wgchen', 'willem', 'ycc'];
console.log(name, arr); // wgchen ['willem', 'ycc']
默认值

为变量设置默认值

let [name, site = 'wgchen'] = ['willem'];

console.log(site); // wgchen
console.log(name); // willem
函数参数

数组参数的使用

function hd([a, b]) {
	console.log(a, b); // wgchen ycc
}

hd(['wgchen', 'ycc']);
管理数组元素 基本使用

使用从0开始的索引来改变数组

let arr = [1, "wgchen", "willem"];
arr[1] = 'wgchen.blog';

console.log(arr); // [1, 'wgchen.blog', 'willem']

向数组追回元素

let arr = [1, "wgchen", "willem"];
arr[arr.length] = 'wgchen.blog';

console.log(arr); // [1, 'wgchen', 'willem', 'wgchen.blog']
扩展语法

使用展示语法批量添加元素

let arr = ["wgchen", "willem"];
let hd = ["wgchen.blog"];
hd.push(...arr);

console.log(hd); // ['wgchen.blog', 'wgchen', 'willem']
push 压入元素

压入元素,直接改变元数组,返回值为数组元素数量

let arr = ["wgchen", "willem"];
console.log(arr.push('ycc', 'haoren')); // 4
console.log(arr); // ['wgchen', 'willem', 'ycc', 'haoren']

根据区间创建新数组

function rangeArray(begin, end) {
    const array = [];
    for (let i = begin; i  (user.name = "张三"));
console.log(find); // {name: '张三'}
findIndex 返回索引值

findIndex 与 find 的区别是返回索引值,参数也是 : 当前值,索引,操作数组。

查找不到时返回 -1

let arr = [7, 3, 2, '8', 2, 6];

console.log(arr.findIndex(function (v) {
	return v == 8;
})); //3
find 原理

下面使用自定义函数

let arr = [1, 2, 3, 4, 5];

function find(array, callback) {
  for (const value of array) {
    if (callback(value) === true) return value;
  }
  return undefined;
}

let res = find(arr, function(item) {
  return item == 23;
});

console.log(res); // undefined

解释 function(item) 里的 item 就是 callback(value) 里的value。

let arr = [1, 2, 3, 4, 5];
function find(array, callback) {
  for (const value of array) {
    if (callback(value) === true) return value;
  }
  return undefined;
}
let res = find(arr, function(item) {
    console.log(item);
  return item == 5;
});
console.log(res);

在这里插入图片描述 下面添加原型方法实现

let arr = [1, 2, 3, 4, 5];

Array.prototype.findValue = function(callback) {
  for (const value of this) {
    if (callback(value) === true) return value;
  }
  return undefined;
};

let re = arr.findValue(function(item) {
  return item == 2;
});
console.log(re); // 2
数组排序 reverse 反转数组顺序
let arr = [1, 4, 2, 9];
console.log(arr.reverse()); //[9, 2, 4, 1]
sort 每次使用两个值进行比较

sort 每次使用两个值进行比较 Array.sort((a,b)=>a-b

  • 返回负数 a 排在 b 前面,从小到大
  • 返回正数 b 排在a 前面
  • 返回 0 时不动

默认从小于大排序数组元素

let arr = [1, 4, 2, 9];
console.log(arr.sort()); //[1, 2, 4, 9]

使用排序函数从大到小排序,参数一与参数二比较,返回正数为降序负数为升序

let arr = [1, 4, 2, 9];

console.log(arr.sort(function (v1, v2) {
	return v2 - v1;
})); // [9, 4, 2, 1]

下面是按课程点击数由高到低排序

let lessons = [
  { title: "媒体查询响应式布局", click: 78 },
  { title: "FLEX 弹性盒模型", click: 12 },
  { title: "MYSQL多表查询随意操作", click: 99 }
];

let sortLessons = lessons.sort((v1, v2) => v2.click - v1.click);
console.log(sortLessons);

在这里插入图片描述

排序原理
let arr = [1, 5, 3, 9, 7];

function sort(array, callback) {
  for (const n in array) {
    for (const m in array) {
      if (callback(array[n], array[m])  elem ? max : elem;
  }
  return max;
}

console.log(arrayMax([1, 3, 2, 9]));
迭代器方法

数组中可以使用多种迭代器方法,迭代器后面章节会详解。

keys 通过迭代对象获取索引
const hd = ['wgchen', 'willem'];
const keys = hd.keys();
console.log(keys.next());
console.log(keys.next());

在这里插入图片描述

获取数组所有键

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const key of arr.keys()) {
  console.log(key);
}

在这里插入图片描述 使用 while 遍历

let arr = ["wgchen", "willem", "ycc"];
let i = 0;
while (arr[i]) {
    console.log(arr[i]);
    i++;
}

在这里插入图片描述

values 通过迭代对象获取值
let arr = ["wgchen", "willem", "ycc"];
const values = arr.values();

console.log(values.next()); // {value: 'wgchen', done: false}
console.log(values.next()); // {value: 'willem', done: false}
console.log(values.next()); // {value: 'ycc', done: false}

获取数组的所有值

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const value of arr.values()) {
  console.log(value);
}
entries 返回数组所有键值对

下面使用解构语法循环

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const [key, value] of arr.entries()) {
  console.log(key, value);
}

在这里插入图片描述 解构获取内容(对象章节会详细讲解)

const hd = ["wgchen", "willem"];
const iterator = hd.entries();

let {done,value: [k, v]} = iterator.next();

console.log(v); // wgchen
扩展方法 every 用于递归的检测元素

要所有元素操作都要返回真结果才为真。

查看班级中同学的JS成绩是否都及格

const user = [
  { name: "李四", js: 89 },
  { name: "马六", js: 55 },
  { name: "张三", js: 78 }
];
const resust = user.every(user => user.js >= 60);
console.log(resust); // false

标题的关键词检查

let words = ['wgchen', '北京'];
let title = 'wgchen不断分享技术教程北京';

let state = words.every(function (item, index, array) {
  return title.indexOf(item) >= 0;
});

console.log(state); // true

// 标题必须包含所有关键词
if (state == false) console.log('标题必须包含所有关键词'); 
some 递归的检测元素

使用 some 函数可以递归的检测元素,如果有一个返回 true,表达式结果就是真。第一个参数为元素,第二个参数为索引,第三个参数为原数组。

下面是使用 some 检测规则关键词的示例,如果匹配到一个词就提示违规。

let words = ['wgchen', '北京', '武汉'];
let title = 'wgchen不断分享技术教程'

let state = words.some(function (item, index, array) {
	return title.indexOf(item) >= 0;
});

if (state) console.log('标题含有违规关键词'); // 标题含有违规关键词
filter 滤数据中元素

使用 filter 可以过滤数据中元素,下面是获取所有在CSS栏目的课程。

let lessons = [
  {title: '媒体查询响应式布局',category: 'css'},
  {title: 'FLEX 弹性盒模型',category: 'css'},
  {title: 'MYSQL多表查询随意操作',category: 'mysql'}
];

let cssLessons = lessons.filter(function (item, index, array) {
  if (item.category.toLowerCase() == 'css') {
    return true;
  }
});

console.log(cssLessons);

在这里插入图片描述 我们来写一个过滤元素的方法来加深些技术

function except(array, excepts) {
  const newArray = [];
  
  for (const elem of array)
    if (!excepts.includes(elem)) newArray.push(elem);
    
  return newArray;
}

const array = [1, 2, 3, 4];
console.log(except(array, [2, 3])); // [1,4]
map 映射在数组所有元素上应用函数

使用 map 映射可以在数组的所有元素上应用函数,用于映射出新的值。

获取数组所有标题组合的新数组

let lessons = [
  {title: '媒体查询响应式布局',category: 'css'},
  {title: 'FLEX 弹性盒模型',category: 'css'},
  {title: 'MYSQL多表查询随意操作',category: 'mysql'}
];

console.log(lessons.map(item => item.title));

在这里插入图片描述

为所有标题添加上 wgchen

let lessons = [
  {title: '媒体查询响应式布局',category: 'css'},
  {title: 'FLEX 弹性盒模型',category: 'css'},
  {title: 'MYSQL多表查询随意操作',category: 'mysql'}
];

lessons = lessons.map(function (item, index, array) {
    item.title = `[wgchen] ${item['title']}`;
    return item;
});

console.log(lessons);

在这里插入图片描述

reduce 迭代数组的所有元素

使用 reduce 与 reduceRight 函数可以迭代数组的所有元素,reduce 从前开始 reduceRight 从后面开始。下面通过函数计算课程点击数的和。

第一个参数是执行函数 第二个参数为初始值

  • 传入第二个参数时将所有元素循环一遍
  • 不传第二个参数时从第二个元素开始循环

函数参数说明如下

参数说明prev上次调用回调函数返回的结果cur当前的元素值index当前的索引array原数组 使用 reduce 实现数组去重
let arr = [1, 2, 6, 2, 1];

let filterArr = arr.reduce((pre, cur, index, array) => {
  if (pre.includes(cur) === false) {
      pre = [...pre, cur];
  }
  return pre;
}, [])

console.log(filterArr); // [1,2,6]
示例
输出了:100

const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num;
}

定义和用法

reduce() 方法将数组缩减为单个值。 reduce() 方法为数组的每个值(从左到右)执行提供的函数。

函数的返回值存储在累加器中(结果/总计)。 注释:对没有值的数组元素,不执行 reduce() 方法。 注释:reduce() 方法不会改变原始数组。

const numbers = [175, 50, 25];
numbers.reduce(myFunc);

function myFunc(total, num) {
  console.log(total,num);
}

在这里插入图片描述

const numbers = [175, 50, 25,30];
numbers.reduce(myFunc);

function myFunc(total, num) {
  console.log(total,num);
}

在这里插入图片描述

统计元素出现的次数
function countArrayELem(array, elem) {
  return array.reduce((total, cur) => (total += cur == elem ? 1 : 0), 0);
}

let numbers = [1, 2, 3, 1, 5];
console.log(countArrayELem(numbers, 1)); //2
取数组中的最大值
function arrayMax(array) {
  return array.reduce(
  	(max, elem) => (max > elem ? max : elem), array[0]
  );
}

console.log(arrayMax([1, 3, 2, 9]));
取价格最高的商品
let cart = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

function maxPrice(array) {
  return array.reduce(
    (goods, elem) => (goods.price > elem.price ? goods : elem),
    array[0]
  );
}
console.log(maxPrice(cart));

在这里插入图片描述

计算购物车中的商品总价
let cart = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

const total = cart.reduce(
	(total, goods) => total += goods.price, 0
);
console.log(total); //40600
获取价格超过1万的商品名称
let goods = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

function getNameByPrice(array, price) {
  return array.reduce((goods, elem) => {
    if (elem.price > price) {
      goods.push(elem);
    }
    return goods;
  }, []).map(elem => elem.name);
}

console.table(getNameByPrice(goods, 10000));

在这里插入图片描述

动画案例

在这里插入图片描述




    
    wgchen



    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #2c3e50;
    }
  
    * {
      padding: 0;
      margin: 0;
    }
    div {
      color: #9b59b6;
      font-size: 5em;
      font-weight: bold;
      text-transform: uppercase;
      cursor: pointer;
    }
    div > span {
      position: relative;
      display: inline-block;
    }
    .changeColor {
      animation-name: changeColor;
      animation-duration: 1s;
      animation-direction: alternate;
      animation-iteration-count: 2;
      animation-timing-function: linear;
    }
    @keyframes changeColor {
      50% {
        color: #f1c40f;
        transform: scale(1.5);
      }
      to {
        color: #9b59b6;
        transform: scale(0.5);
      }
    }
  
  
  
    wgchen.blog.csdn.net
  
  
  
    let div = document.querySelector("div");
    /*
        console.log([...div.textContent]); 
        ['w', 'g', 'c', 'h', 'e', 'n', '.', 'b', 'l', 'o', 'g', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't']
    */

    [...div.textContent].reduce((pre, cur, index) => {
        // console.log(pre); // 0
      pre == index && (div.innerHTML = "");

      let span = document.createElement("span");
      span.textContent = cur;
      div.appendChild(span);

      span.addEventListener("mouseover", function() {
        this.classList.add("changeColor");
      });

      span.addEventListener("animationend", function() {
        this.classList.remove("changeColor");
      });

    }, 0);
  


关注
打赏
1665558895
查看更多评论
立即登录/注册

微信扫码登录

0.0770s