慕课前端入门-js内置对象

1. 数组

js数组特点:

  1. 可以保存各种类型的元素
  2. 同一个数组,元素类型可以不同
  3. 数组的大小,是可以动态调整的

1.1 创建数组

创建数组的基本方式有2种:

  • 使用Array构造函数 new Array()
    说明:
    1.预先知道数组要保存的元素数量
    2.向Array构造函数中传递数组应包含的元素
var colors = new Array(3);//指定数组长度
var nums = new Array(1,3,6,9);//指定元素
  • 使用数组字面量表示法
    由一对包含数组元素的方括号[] 表示,多个元素之间用逗号隔开
var colors = ["red", "yellow", "green"];

1.2 数组元素的读写

读取和设置值时,使用方括号[]并提供相应的索引
说明:索引是从0开始的正整数

array[index]=value

1.3 数组长度length

//说明通过设置length可以从数组的末尾移除元素或向数组中添加元素,不建议这样使用
var arr = ["a","b","c","d"];
console.log(arr.length);//3
//当把一个值放在超出当前数组大小的位置上时,会重新计算数组长度值,长度值等于最后一个元素的索引+1
arr[99]="z"
arr.length;//100

1.4 数组的栈方法

方法说明示例
push语法:arrayObject.push(el1, el2...);
功能:向数组中追加元素
返回值:操作后,数组的长度
var color = ["green", "yellow"];
console.log(color.push("hello", "world"));//4

console.log(color.unshift("java", "python"));//6

console.log(color.pop());//world

console.log(color.shift());//java

console.log(color.join("_"));

//python_green_yellow_hello

console.log(color.reverse());

//["hello", "yellow", "green", "python"]

console.log(color.sort());

//["green", "hello", "python", "yellow"]

var nums = [8,5,9,6,7,"a"];

console.log(nums.sort());
//[5, 6, 7, 8, 9, "a"]
unthift语法:arrayObject.unshift(el1, el2...);
功能:把它的参数顺序添加到数组的开头
返回值:操作后,数组的长度
pop语法:arrayObject.pop()
功能:删除数组的最后一个元素
返回值:被删除的那个元素
shift语法:arrayObject.shift()
功能:删除数组的第一个元素
返回值:被删除的那个元素
join语法:arrayObject.join(separator)
功能:用于把数组中的所有元素合并为一个字符串
返回值:字符串
reverse语法:arrayObject.reverse()
功能:将数组中元素的反序
返回值:数组
sort语法:arrayObject.sort(sortby)
功能:用于对数组的元素进行排序
返回值:数组
说明:
  1. 即使数组中的每一项都是树枝,sort()方法比较的也是字符串
  2. sort()方法可以接受一个比较函数作为参数
cancat语法:arrayObject.concat(arrayX,arrayX...);
功能:用于连接两个或多个数组
返回值:数组
var arr1=['a','b','c'],arr2=[1,2,3];
console.log(arr1.concat(arr2));
console.log(arr1.concat(arr2,"hello","world"));
slice切片语法:arrayObject.slice(start,end)
功能:从已有的数组中返回特定的元素
参数:
  1. start,必选:起始位置,包含
  2. end:可选,结束位置,不包含
  3. 如果没有指定end,切分的数组包含从start到数组结束的所有元素
  4. 参数为负数,则用参数的长度加上负数来确定相应的位置
  5. 没有结果,就返回空数组
返回值:数组
var arr = "hello world".split("");
console.log(arr.slice(5));
console.log(arr.slice(5,7));
console.log(arr.slice(-7,-5))
splice语法:arrayObject.splice(index, count, el1, el2...)
功能:删除、替换、插入
参数:
  1. index:起始位置,必填
  2. count:删除元素数量。删除选填,插入为0,替换不为0
  3. el1,el2...:有是替换和插入;没有是删除
返回值:删除元素组成的数组,没有,就返回空数组。
var arr = "abcdefghijk".split("");
//delete 删除从index开始count个元素;
//count不填,删除从index处开始的所有值;
//count为0,不会删除元素
console.log(arr.splice(4,2)); //["e", "f"]
console.log(arr.splice(1));
//["b", "c", "d", "g", "h", "i", "j", "k"]
//insert count=0
console.log(arr.splice(1,0,5,6,7)); //[]
console.log(arr); //["a", 5, 6, 7]
//替换 count!=0
console.log(arr.splice(1,2,'x','y'));// [5, 6]
console.log(arr); //["a", "x", "y", 7]
index()
lastIndexOf()
语法:arrayObject.indexOf(searchValue, startIndex)
功能:指定位置开始查找
参数:
  1. searchValue:必需,要查找的元素
  2. startIndex:可选,起始位置
返回值:number 找到返回索引;未找到,返回-1
arrayObject.lastIndexOf(searchValue,startIndex)与indexOf相反
var nums = [1,7,5,7,8,1,6,9];
console.log(nums.indexOf(7));//1
console.log(nums.lastIndexOf(7));//3

1.5 示例,如何复制一个数组

	var arr = "hello world".split(""),newArr=[];
	//方法1
	for(var i=0;i<arr.length;i++){
		newArr.push(arr[i]);
	}
	console.log(newArr);
	//方法2
	newArr=[].concat(arr);
	console.log(newArr);
	//方法3
	newArr = arr.slice(0);
	console.log(newArr);

1.6 封装一个方法实现indexOf的功能

	function ArrayIndexOf(arr, value){
		//检测value在arr中出现的位置
		for(var i=0;i<arr.length;i++){
			if(arr[i]===value){
				//此处使用全等操作符,即要求查找的元素必须和值完全相等
				return i;
			}
		}
		return -1;
	}

2. String

方法说明示例
charAt语法:stringObject.charAt(index);
功能:返回字符串中指定位置的字符;没有结果,返回空字符串
说明:ECMAScript5中可用[index]来访问字符串中特定的字符,但是IE7及更早的浏览器会返回undefined
var a = "hello world";

console.log(a[1]);//e

console.log(a.charAt(2));//l

console.log(a.charCodeAt(3));//108

console.log(a.indexOf("or"));//7

console.log(a.lastIndexOf("o"));//7

console.log(a.slice(7));//orld

console.log(a.slice(-5, -2));//wor

console.log(a.substring(2, -5));//he

console.log(a.substr(6,3));//wor

console.log(a.substr(-5,4));//worl

console.log(a.split(""));
//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

console.log(a.replace("o","z"));//hellz world

"hello".toUpperCase();//HELLO

"HELLO".toLowerCase();//"hello"
charCodeAt 语法:stringObject.charCodeAt(index);
功能:返回字符串中指定位置的字符编码
indexOf 语法:stringObject.indexOf("or")
功能:返回子串在字符串中第一次出现的位置;没有找到,返回-1
lastIndexOf 语法:stringObject.lastIndexOf("or")
功能:返回子串在字符串中最后一次出现的位置;没有找到返回-1
slice 语法:stringObject.slice(start, end)
功能:截取字符串
参数:
  1. start:必需,指定开始位置
  2. end:可选,表示结束位置。没有默认到最后

说明
  1. end不在截取范围内
  2. 当参数为负数时,会将传入的负值与字符串的长度相加
substring 语法同slice
区别:
  1. 当参数为负数时,自动将参数转换为0
  2. 会把较小的数作为起始位置,将较大的数作为结束位置
substr 语法:stringObject.substr(start, len);
功能:截取字符串
参数说明:
  1. start:必需,指定子字符串的开始位置。
  2. len:可选,表示截取的字符总数,省略时截取到字符串的末尾。
  3. 当start为负数时,会将传入的负值与字符串的长度相加。
  4. 当len为负数时,会返回空字符串。
split 语法:stringObject.split(separator)
功能:把一个字符串分割成字符串数组
返回值:Array
replace 语法:stringObject.replace(regexp/substr, replacement)
功能:替换
返回值:string
参数:
  1. regexp:必需,规定子字符串或要替换的模式的正则表达式
  2. replacement:必需,字符串
缺点:只能替换第一个
toUpperCase 语法:stringObject.toUpperCase()
功能:把字符串转换为大写
toLowerCase 语法:stringObject.toLowerCase()
功能:把字符串转换为小写

2.1 示例:获取文件名后缀

function getFileFormat(fileName) {
	// body...
	var pos = fileName.lastIndexOf(".")+1;
	return fileName.slice(pos);
}
console.log(getFileFormat("test.sh")); //sh

2.2 示例:将下划线替换为驼峰

function getHumpName(str){
	var arr = str.split("_");
	var result = arr[0];
	for(var i=1;i<arr.length;i++){
		result += arr[i].slice(0,1).toUpperCase()+arr[i].slice(1);
	}
	return result;
}
console.log(getHumpName("back_left_border")); //backLeftBorder

3. Math

方法说明示例
min 语法:Math.min(num1,num2...)
功能:返回一组数中的最小值
说明:只要这组数中出现一个非数字,就返回NaN
console.log(Math.min(1,2,5,6,0));//0
console.log(Math.max(1,2,5,6,0));//6
console.log(Math.ceil(1.8));//2
console.log(Math.floor(1.8));//1
console.log(Math.round(1.8));//2
console.log(Math.random());//随机数
max 语法:Math.max(num1,num2...)
功能:返回一组数中的最大值
ceil 语法:Math.ceil(num)
功能:向上取整,即返回大于num的最小整数
floor 语法:Math.floor(num)
功能:向下取整,返回num的整数部分
round 语法:Math.round(num)
功能:将数值四舍五入为最接近的整数
abs 语法:Math.abs(num)
功能:返回num的绝对值
random 语法:Math.random()
功能:返回[0,1)之间的一个随机数

3.1 示例

利用random,取固定区间的随机整数

//公式:random = Math.floor( Math.random() * (m-n+1) + n );
function	getRandom(n,m){
	var choise = m -n + 1;
	return Math.floor(Math.random() * choise + n);
}
var random1 = getRandom(2,6);
console.log(random1)

4. Date

4.1 创建Date对象

  1. new Date
  2. new Date(year, month, day, hours, minutes, seconds, milliseconds) year和month必需;一个参数会将毫秒数处理
  3. new Date(millisecond)
  4. new Date(string)
var day1 = new Date();
var day2 = new Date(2020,8,5,17,56,32,0);
var day3 = new Date(1234567890);
var day4 = new Date("2020-08-17 12:56:17");

4.2 获取和设置Date

获取设置示例
getFullYear()获取年份setFullYear(year)设置年份
function toDate(dateObject){	
  var weeks=["日","一","二","三","四","五","六"],
    year=dateObject.getFullYear(),
    month=dateObject.getMonth()+1,
    date=dateObject.getDate(),
    week = weeks[dateObject.getDay()],
    hours=dateObject.getHours(),
    minutes=dateObject.getMinutes(),
    seconds=dateObject.getSeconds(),
    times=dateObject.getTime(),
    time=year+"年"+month+"月"+date+"日"+hours+"时"+minutes+"分"+seconds+"秒 星期"+week;
    console.log(time);
    console.log(times);
}
toDate(new Date());
var a = new Date();
a.setFullYear(2011);
a.setMonth(13);
a.setDate(32);
a.setHours(25);
a.setMinutes(61);
a.setSeconds(61);
toDate(a);
getMonth()获取月份0-11setMonth(mon)设置月份
getDate()获取月份中的某一天setDate()设置日期
getDay()返回周几,0-6setDay()设置周几
getHours()获取小时setHours()设置小时
getMinutes()获取分setMinutes()设置分
getSeconds()获取秒setSeconds()设置秒
getTime()获取毫秒数setTime()设置毫秒数

日期设置具有容错能力。以示例来说:

a.setFullYear(2011);//2011年
a.setMonth(13);//13-12=1,加1年,即2012年2月
a.setDate(32);//32-29=3,加1个月,转换后2012年3月3日
a.setHours(25);//25-24,加1天,2012年3月4日1点
a.setMinutes(61);//61-60=1,加1小时,2012年3月4日2点1分
a.setSeconds(61);//61-60=1,加1分钟,2012年3月4日2点2分1秒

4.3 Date日期运算

//日期加减操作
//方法1
var b = new Date();
b.setDate(b.getDate()+50);
toDate(b);
//方法2
var c = new Date();
var year = c.getFullYear();
var month = c.getMonth();
var day = c.getDate();
var temp = new Date(year, month, day+50);
toDate(temp)
原文地址:https://www.cnblogs.com/csj2018/p/13658350.html