js对象简介、内置对象
对象、内置对象
@jarringslee
对象
对象(object)是js的一种引用数据类型,是一种无序的数据集合“ul”(类比于数组,有序的数据集合“ol”)。
基本上等于结构体。
对象的声明
//基本方法
let 对象名 = {声明元素
}
对象中的元素一般由属性和方法组成
-
属性:对象的信息、特征。一般为名词性的键值对(
属性名:属性值
),多个键值对之间用逗号分隔。属性就是依附在对象上的变量(门面是变量,对象内就是属性)。
属性名可以用单、双引号包裹(一般情况下省略),除非遇到特殊符号如空格、中横线作为属性名时。
let obj = {name:'ljl',age:18,gender:'man',sing: function(){document.write('lalalala')}//若属性名为字符串、带有下划线则需带上单引号'best-friend':'lihua' }
-
方法:对象的功能、行为。
方法名:函数
对象的增删改查
查找、访问元素 对象.属性名
或者 对象.['属性名']
(中括号中不管是不是字符串都必须带上单引号)
修改元素 直接重新赋值即可
增加元素 对象.新建属性名 = 赋值
删除元素 delete delete 对象.属性名
遍历对象 for(in)语法
for(in)语法遍历数组:(输出的下标是字符串类型)
let arr = ['aa', 'b', 'ccc'] for (let k in arr) { console.log(k) //顺序遍历数组的下标,即输出:012。 //注意:这里输出的下标是字符串类型 document.write(arr[k]) }
一般不用这个方法遍历数组。
该语法中,输出属性值的方法必须是对象.['属性名']
let obj = {name:'ljl',age:18,gender:'man','ex-bf':'cjx'
}
for (let k in obj){console.log(k) //顺序打印出属性名document.write(obj[k])
}
对象数组
let people = [{name:'ljl', age:18, gender:'man', 'ex-bf':'cjx'},{name:'ljl', age:18, gender:'man', 'ex-bf':'cjx'},{name:'ljl', age:18, gender:'man', 'ex-bf':'cjx'},{name:'ljl', age:18, gender:'man', 'ex-bf':'cjx'}
]
//遍历对象数组
for (let i = 0; i < people.length; i++) {console.log(people[i].age)document.write(people[i]['ex-bf'])
}
对象数组及js综合小案例 渲染学成在线
在原来学习css的基础上,利用js插入不同图片、标题和观看人数。
明显可以利用到一个包含图片、文本内容和数字的对象并集合成一个对象数组,在<script>
中声明之后用for循环按照html标签模版输出即可。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>学成在线首页</title><style>* {margin: 0;padding: 0;}.w {width: 1200px;margin: auto;}body {background-color: #f3f5f7;}li {list-style: none;}a {text-decoration: none;}.clearfix:before,.clearfix:after {content: "";display: table;}.clearfix:after {clear: both;}.clearfix {*zoom: 1;}.box {margin-top: 30px;}.box-hd {height: 45px;}.box-hd h3 {float: left;font-size: 20px;color: #494949;}.box-hd a {float: right;font-size: 12px;color: #a5a5a5;margin-top: 10px;margin-right: 30px;}/* 把li 的父亲ul 修改的足够宽一行能装开5个盒子就不会换行了 */.box-bd ul {width: 1225px;}.box-bd ul li {position: relative;top: 0;float: left;width: 228px;height: 270px;background-color: #fff;margin-right: 15px;margin-bottom: 15px;transition: all .3s;}.box-bd ul li a {display: block;}.box-bd ul li:hover {top: -8px;box-shadow: 0 15px 30px rgb(0 0 0 / 10%);}.box-bd ul li img {width: 100%;}.box-bd ul li h4 {margin: 20px 20px 20px 25px;font-size: 14px;color: #050505;font-weight: 400;}.box-bd .info {margin: 0 20px 0 25px;font-size: 12px;color: #999;}.box-bd .info span {color: #ff7c2d;}</style>
</head><body><!-- 4. box核心内容区域开始 --><div class="box w"><div class="box-hd"><h3>精品推荐</h3><a href="#">查看全部</a></div><div class="box-bd"><ul class="clearfix"><script>let data = [{src: './images/course01.png',title: 'Think PHP 5.0 博客系统实战项目演练',num: 1125},{src: './images/course02.png',title: 'Android 网络动态图片加载实战',num: 357},{src: './images/course03.png',title: 'Angular2 大前端商城实战项目演练',num: 22250},{src: './images/course04.png',title: 'Android APP 实战项目演练',num: 389},{src: './images/course05.png',title: 'UGUI 源码深度分析案例',num: 124},{src: './images/course06.png',title: 'Kami2首页界面切换效果实战演练',num: 432},{src: './images/course07.png',title: 'UNITY 从入门到精通实战案例',num: 888},{src: './images/course08.png',title: 'Cocos 深度学习你不会错过的实战',num: 590},]for (let i = 0; i < data.length; i++) {document.write(`<li><a href="#"><img src="${data[i].src}" alt=""><h4>${data[i].title}</h4><div class="info"><span>高级</span> • <span>${data[i].num}</span>人在学习</div></a></li>`)}</script></ul></div></div></body></html>
内置对象
js内置对象,方便我们调用,提高开发效率
例如console.log
document.write
内置对象Math 类似于C语言中提供数学运算函数的函数库,这里我们通过调用对象元素的形式进行调用
方法 | 作用 | 示例 |
---|---|---|
Math.PI | 圆周率 π | 3.141592653589793 |
Math.E | 自然常数 e | 2.718281828459045 |
Math.LN2 | 2 的自然对数 | 0.6931471805599453 |
Math.LN10 | 10 的自然对数 | 2.302585092994046 |
Math.LOG2E | 以 2 为底 e 的对数 | 1.4426950408889634 |
Math.LOG10E | 以 10 为底 e 的对数 | 0.4342944819032518 |
Math.SQRT2 | 2 的平方根 | 1.4142135623730951 |
Math.SQRT1_2 | 1/2 的平方根 | 0.7071067811865476 |
Math.random() | 生成 [0, 1) 之间的随机小数 | 0.72634… |
Math.ceil(x) | 向上取整 | Math.ceil(4.2) → 5 |
Math.floor(x) | 向下取整 | Math.floor(4.9) → 4 |
Math.round(x) | 四舍五入 | Math.round(4.5) → 5 |
Math.max(a,b,...) | 取最大值 | Math.max(3, 7, 2) → 7 |
Math.min(a,b,...) | 取最小值 | Math.min(3, 7, 2) → 2 |
Math.pow(base, exp) | 幂运算 base^exp | Math.pow(2, 3) → 8 |
Math.abs(x) | 绝对值 | Math.abs(-5) → 5 |
随机生成函数Math.random()
-
Math.random()
永远返回[0, 1)
区间内的随机小数,即 含 0 不含 1。 -
0 → 10 的随机整数
Math.floor(Math.random() * (10 + 1))
先放大 11 倍,再向下取整 → 得到 0‒10 共 11 个值。
-
5 → 10 的随机整数
Math.floor(Math.random() * (10 - 5 + 1)) + 5
区间长度
(10-5+1)=6
,再加偏移量 5 → 得到 5‒10。 -
随机数组下标
const idx = Math.floor(Math.random() * arr.length); const randomItem = arr[idx];
其中arr.length已经是下标最大值加一了
-
通用公式:N → M 的随机整数
Math.floor(Math.random() * (M - N + 1)) + N
// 生成 N~M 之间的随机整数(包含 N 和 M) function getRandom(N, M) {return Math.floor(Math.random() * (M - N + 1)) + N; }console.log(getRandom(4, 8)); // 示例:输出 4~8 之间的随机整数
“区间长度乘随机,再向下取整,最后加起点”。
随机函数小练习1 猜数字
很简单的if分支语句练习,重点是利用随机函数生成一个数字,并用if语句判断大小。在这个基础上可以用for循环设置规定的猜测次数,注意用布尔变量来检测次数是否用尽。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><script>// 无限次数猜测// function getRandom(N, M) {// return Math.floor(Math.random() * (M - N + 1)) + N;// }// let random = getRandom(1, 20)// while (true) {// let num = +prompt('请输入您猜的数字')// if (num > random) alert('猜的有点大了')// else if (num < random) alert('猜的有点小了')// else {// alert('猜对啦,真厉害!')// break// }// }function getRandom(N, M) {return Math.floor(Math.random() * (M - N + 1)) + N;}let random = getRandom(1, 20)let flag = truefor (let i = 1; i <= 5; i++) {let num = +prompt('请输入您猜的数字')if (num > random) alert('猜的有点大了')else if (num < random) alert('猜的有点小了')else {alert('猜对啦,真厉害!')flag = falsebreak}}if (flag) alert('你失败啦!')</script>
</body></html>
随机函数小练习2 随机颜色
也没有什么难点,用for循环输出随机数组。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>random color</title>
</head><body><script>function rcolor(flag = true) {if (flag) {let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']// let f1 = Math.floor(Math.random() * 16)// let f2 = Math.floor(Math.random() * 16)// let f3 = Math.floor(Math.random() * 16)// let f4 = Math.floor(Math.random() * 16)// let f5 = Math.floor(Math.random() * 16)// let f6 = Math.floor(Math.random() * 16)// return `#${arr[f1]}${arr[f2]}${arr[f3]}${arr[f4]}${arr[f5]}${arr[f6]}`let str = '#'for (let i = 1; i <= 6; i++) {let f = Math.floor(Math.random() * arr.length)str += arr[f]}return str}else {let r = Math.floor(Math.random() * 256)let g = Math.floor(Math.random() * 256)let b = Math.floor(Math.random() * 256)return `rgb(${r},${g},${b})`}}// let bool = +prompt('真还是假?')document.write(rcolor(1))</script>
</body></html>