js 数组array

186 阅读2分钟

基本定义和特点

写法:(=和[]是必有的)

let  数组名=['内容0','内容1','内容2','内容3','内容4']

编号是从0开始的

指定数组里的某个数据:(数组名[n])

(name.length)表示数组有几个值,//=n

console.log(name[10])//指定数组里没有的,直接会输出undefined

可以存储任意类型的数据

数组使用的案例:

求数组的和

let  i=[1,3,5,6,7]
        let  sum=0
for (let index = 0; index < i.length; index++) {
    sum+=i[index]
}
console.log(sum)

求最大(小)值

let  i=[1,3,5,6,7]
        let  max=i[0]
for (let index = 0; index < i.length; index++) {
   (max>=i[0])&&(max=i[index])
}
console.log(max)

数组增删改

增:(arr.push()加尾+arr.unshift(新增的内容) 加头)

数组筛选案例(把大于等于 10 的元素选出来,放到新数组里)

let  arr=[2,3,44,5,66,33]
        let  Newarr=[]
        for (let index = 0; index <arr.length; index++) {
           (arr[index]>=10)&&(Newarr.push(arr[index]))
        }
        console.log(Newarr)

删:(数组. pop() 删尾+数组. shift()删头+数组. splice() 方法 删除指定元素)

注意:splice(想要删除的元素的下标,想要删除几个(可以写0),想要添加的元素) ..[添加的元素会显示在所选元素的前面]

一些小技巧

获取数组的最后一个元素 arr[arr.length - 1]

2 新增或者修改数组元素 arr[10]='南瓜'
1 如果 10这个位置已经有元素 那么 就是修改 2 如果 10这个位置没有元素 添加就可以了 最终数组的度变成 10+1
3 数组 可以存放任意类型的数据 可以这么做,但是不建议 我们建议 一个数组内的数据类型要统一!! 4 数组快速清空或者删除元素的方式 arr.length = 0

综合大案例:根据数据生成柱形图

* {margin: 0;
padding: 0;
 box-sizing: border-box;
}
ul {
list-style: none;
width: 1000px;
height: 600px;
margin: 100px auto;
display: flex;
justify-content: space-around;
background-color: aqua;
align-items: flex-end;
 }
li {
width: 100px;
background-color: pink;
 position: relative;
}
span {
 position: absolute;
top: -30px;
 left: 50%;
 transform: translateX(-50%);
 }
div {
 position: absolute;
 width: 100%;
text-align: center;
 /* 相对于父元素的高 */
 top: 100%;
background-color: red;
 }
```js
:

/* 动态获取用户输入的高度 ,然后把高度都设置到一个数组即可 1 弹出4个窗口,让用户输入数据
*/ let liHtml = <ul>; let liHeight = []; // for循环来弹出4个窗口 获取内容 for (let index = 0; index < 4; index++) { // 弹窗获取用户的输入的高度 let height = +prompt(请输入你想要的第${index + 1}个高度数据); // 把数据 添加到数组中 liHeight.push(height); }

  for (let index = 0; index < 4; index++) {
    liHtml += `
    <li style="height:${liHeight[index]}px;"> 
      <span>${liHeight[index]}</span>
第${index + 1}季度
`; } liHtml += ``; document.write(liHtml); ```