js常用方法总结
数组方法
<script type="text/javascript">
let fruits = ["Banana", "Orange", "Apple", "Mango"];
//获取数组长度
fruits.length; //4
// toString() 把数组转换为数组值(逗号分隔)的字符串
fruits.toString(); //Banana,Orange,Apple,Mango
// join() 方法也可将所有数组元素结合为一个字符串。它的行为类似 toString(),但是您还可以规定分隔符
fruits.join(" * "); //Banana * Orange * Apple * Mango
// pop() 删除并返回数组的最后一个元素
const f1 = fruits.pop(); // "Mango"
// shift() 把数组的第一个元素从其中删除,并返回第一个元素的值
const f2 = fruits.shift(); //"Banana"
// push() 向数组的末尾添加一个或多个元素,并返回新的长度。
fruits.push("Kiwi", "lemon"); //4
//unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。
fruits.unshift("Lemon"); //5
console.log(new Array(5).fill(1)); //数组填充[ 1, 1, 1, 1, 1 ]
// splice() 从数组中添加/删除项目,然后返回被删除的项目
//参数1 规定添加/删除项目的位置, 参数2 要删除的项目数量,设置为0则不会删除项目 其余参数定义要添加的新元素
fruits.splice(2, 0, "Lemon", "Kiwi"); //['Lemon', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Kiwi', 'lemon']
// concat() 方法通过合并(连接)现有数组来创建一个新数组
let fruits1 = ["lemon"];
let fruits2 = ["waterlemon"];
let fruits3 = fruits.concat(fruits1, fruits2); //['Lemon', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Kiwi', 'lemon', 'lemon', 'waterlemon']
// slice() 选取数组的一部分,并返回一个新数组,该方法会从开始参数选取元素,直到结束参数(不包括)为止
let somFriuts = fruits.slice(1, 3); //['Orange', 'Lemon']
// sort() 方法以字母顺序对数组进行排序
fruits.sort(); //['Apple', 'Kiwi', 'Kiwi', 'Lemon', 'Lemon', 'Orange', 'lemon']
// reverse() 方法反转数组中的元素
fruits.reverse(); // ['lemon', 'Orange', 'Lemon', 'Lemon', 'Kiwi', 'Kiwi', 'Apple']
// sort() 方法以数字顺序对数组进行排序
var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) {
return a - b;
}); //[1, 5, 10, 25, 40, 100]
var cars = [
{ type: "Volvo", year: 2016 },
{ type: "Saab", year: 2001 },
{ type: "BMW", year: 2010 },
];
cars.sort(function (a, b) {
return a.year - b.year;
}); // [{type: 'Saab', year: 2001},{type: 'BMW', year: 2010},{type: 'Volvo', year: 2016}]
// forEach() 方法为每个数组元素调用一次函数(回调函数)
cars.forEach(function (item, index, cars) {
// console.log(item, index, cars);
});
// map() 元素为值类型,新数组改变,原数组不改变。元素为引用类型,原数组会被改变
// 想要原数组不变,可以用下面这种方式解决
const newcars1 = cars.map(function (item, index, cars) {
return Object.assign({ cat: 1 }, item); // 实际上也是浅拷贝
}); //[{cat: 1,type: 'Saab', year: 2001},{cat: 1,type: 'BMW', year: 2010},{cat: 1,type: 'Volvo', year: 2016}]
// filter() 如果返回真,就要,返回假,就不要
const newcars = cars.filter(function (item, index, cars) {
return item.year > 2015;
}); //[{type: 'Volvo', year: 2016}]
// reduce() 方法在每个数组元素上运行函数,以生成单个值,在数组中从左到右工作
// reduceRight() 同reduce(),在数组中从右到左工作
// reduce total为初始值,起初调用时默认为第一个元素,下一次调用时它将变为返回值
let arr = [1, 2, 3, 4, 5];
const total = arr.reduce(function (total, value, index, arr) {
return total + value;
}); //15
// reduce 如果给了它初始值,total的初始值就会变为给定的初始值0
const total1 = arr.reduce(function (total, value, index, arr) {
return total + value;
}, 0); //15
//使用reduce函数计算数组元素个数
function arrayCount(array, item) {
return array.reduce(function (total, cur) {
total += item == cur ? 1 : 0;
return total;
}, 0);
}
console.log(arrayCount(arr, 1)); //1
//使用reduce函数计算数组最大值
function arrayMax(array) {
return array.reduce(function (pre, cur) {
return pre > cur ? pre : cur;
});
}
console.log(arrayMax(arr)); //5
//使用reduce函数处理对象
let cart = [
{ name: "iphone", price: 12000 },
{ name: "mac", price: 18000 },
{ name: "ipad", price: 3200 },
];
function maxPrice(goods) {
return goods.reduce(function (pre, cur) {
return pre.price > cur.price ? pre : cur;
});
}
console.log(maxPrice(cart)); //{name: "mac", price: 18000}
function totalPrice(goods) {
return goods.reduce(function (total, cur) {
return (total += cur["price"]);
}, 0);
}
console.log(totalPrice(cart)); //33200
// every() 方法检查所有数组值是否通过测试
const res = cars.every(function (item, index, cars) {
return item.year > 2010;
});
// some() 方法检查某些数组值是否通过了测试
const res1 = cars.some(function (item, index, cars) {
return item.year > 2015;
});
// indexOf() 搜索数组中的元素,并返回它所在的位置
let a = fruits.indexOf("Apple", 1); //6
// lastIndexOf() 与 indexOf() 类似,但是从数组结尾开始搜索
let c = fruits.lastIndexOf("Apple", 1); //6
// find() 和 findIndex()
const cc = cars.find(function (item) {
return item.name == "mac";
}); // { name: "mac", price: 18000 }
const index = cars.findIndex(function (item) {
return item.name == "mac";
}); //1
// includes() 判断一个数组是否包含一个指定的值。
let b = fruits.includes("Banana"); //false
// join() 返回以指定分割符分割的数组元素的字符串
const str = arr.join(",");
// flat()把数组里嵌套的数组变成一维数组(扁平化)
const arr1 = [
[2, 4],
[4, 7],
];
const arr2 = arr1.flat();
// Array.isArray() 用来判断是不是数据是不是一个数组,返回值为true或false
Array.isArray(arr2); //true
// copyWithin() 从数组的指定位置拷贝元素到数组的另一个指定位置中
//参数1 拷贝的目标位置 参数2 拷贝开始位置 参数3 拷贝结束位置
arr.copyWithin(1, 3);
//数组去重
[...new Set(arr)];
</script>
字符串方法
<script>
// length 属性返回字符串的长度
str.length;
// indexOf() 方法返回字符串中指定文本首次出现的索引(位置)
str.indexOf(subStr, startIdx);
// lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引
str.lastIndexOf(subStr, startIdx);
// search() 方法搜索特定值的字符串,并返回匹配的位置 search() 方法无法设置第二个开始位置参数 indexOf() 方法无法设置更强大的搜索值(正则表达式)
str.search(/\d/g);
// slice() 提取字符串的两个索引之间的部分并在新字符串中返回被提取的部分。该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)
str.slice(7, 13);
// substring() 类似于 slice()。不同之处在于 substring() 无法接受负的索引
str.substring(7, 13);
// substr() 类似于 slice()。不同之处在于第二个参数规定被提取部分的长度
str.substr(7, 6);
// replace() 方法用另一个值替换在字符串中指定的值,返回新字符串,默认地,replace() 只替换首个匹配
var n = str.replace(/MICROSOFT/i, "W3School");
// replace() 方法 如需替换所有匹配,请使用正则表达式的 g 标志(用于全局搜索)
var n = str.replace(/Microsoft/g, "W3School");
// toUpperCase() 把字符串转换为大写
var text2 = text1.toUpperCase();
// toLowerCase() 把字符串转换为小写
var text2 = text1.toLowerCase();
// concat() 连接两个或多个字符串
var text3 = text1.concat(" ", text2);
// trim() 方法删除字符串两端的空白符
var str3 = str.trim();
// charAt() 方法返回字符串中指定下标(位置)的字符串
str.charAt(0);
// charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码
str.charCodeAt(0);
// split() 将字符串转换为数组
txt.split(",");
// match() match() 方法根据正则表达式在字符串中搜索匹配项,并将匹配项作为 Array 对象返回,
// 如果正则表达式不包含 g 修饰符(执行全局搜索),match() 方法将只返回字符串中的第一个匹配项
str.match(/\d/g);
// includes()如果字符串包含指定值,includes() 方法返回 true
text.includes("world", start);
// startsWith()如果字符串以指定值开头,则 startsWith() 方法返回 true,否则返回 false
text.startsWith("Hello", start);
// endsWith()如果字符串以指定值结尾,则 endsWith() 方法返回 true,否则返回 false
text.endsWith("Gates", length);
</script>
时间日期方法
<script>
var d = new Date(); //Fri May 15 2020 15:17:12 GMT+0800 (中國標準時間)
d = new Date(1663726202281); // 参数为毫秒
d = new Date("2022-06-15 15:30:23 453");
d = new Date(2022, 5, 15, 15, 30, 23, 453);
console.log(d.getDate()); // getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)
console.log(d.getDay()); // getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)
console.log(d.getMonth()); // getMonth() 从 Date 对象返回月份 (0 ~ 11)
console.log(d.getFullYear()); // getFullYear() 从 Date 对象以四位数字返回年份
console.log(d.getHours()); // getHours() 返回 Date 对象的小时 (0 ~ 23)
console.log(d.getMinutes()); // getMinutes() 返回 Date 对象的分钟 (0 ~ 59)
console.log(d.getSeconds()); // getSeconds() 返回 Date 对象的秒数 (0 ~ 59)
console.log(d.getMilliseconds()); // getMilliseconds()返回 Date 对象的毫秒(0 ~ 999)
console.log("-------------");
console.log(d.getTime()); //获取时间戳
console.log(d.valueOf()); //获取时间戳
console.log(+d); //获取时间戳
console.log(Date.now()); //获取时间戳
console.log(Date.parse("2022-07-25 14:25:25")); // Date.parse()返回1970年1月1日午夜到指定日期(字符串)的毫秒数
console.log(d.toDateString()); //Wed Jun 15 2022
console.log(d.toString()); //Wed Jun 15 2022 15:30:23 GMT+0800 (中國標準時間)
console.log(d.toJSON()); //2022-06-15T07:30:23.453Z
console.log(d.toISOString()); //2022-06-15T07:30:23.453Z
console.log(d.toLocaleString()); // 2022/6/15 下午3:30:23
d.setDate(15); // setDate() 设置 Date 对象中月的某一天 (1 ~ 31)
d.setMonth(4); // setMonth() 设置 Date 对象中月份 (0 ~ 11)
d.setFullYear(2020); // setFullYear() 设置 Date 对象中的年份(四位数字)
d.setHours(15); // setHours() 设置 Date 对象中的小时 (0 ~ 23)
d.setMinutes(17); // setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)
d.setSeconds(23); // setSeconds() 设置 Date 对象中的秒数 (0 ~ 59)
</script>
遍历方法
<script>
//---------------------数组遍历
var cars = [
{ type: "Volvo", year: 2016 },
{ type: "Saab", year: 2001 },
{ type: "BMW", year: 2010 },
];
// 传统的for循环
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
// for of 方法
for (let item of cars) {
console.log(item);
}
// 迭代器方法
for (let index of cars.keys()) {
console.log(index);
}
for (let item of cars.values()) {
console.log(item);
}
for (let [index, item] of cars.entries()) {
console.log(index, item);
}
// for in 方法
for (let key in cars) {
console.log(key, cars[key]);
}
</script>
Object对象方法
<script>
// Object常用方法
const obj = { a: 1, b: 2 };
// Object.keys()会返回一个给定对象的自身可枚举属性组成的数组
console.log(Object.keys(obj)); //['a','b'];
// Object.values():返回一个给定对象自身的所有可枚举属性值的数组
console.log(Object.values(obj)); //[1,2];
// Object.entries():返回一个给定对象自身可枚举属性的键值对数组
console.log(Object.entries(obj)); //[['a', 1],['b', 2]];
Object.entries(obj).map((entry) => {
console.log(entry); // ['a', 1] ['b', 2]
});
// Object.fromEntries():把键值对列表转换为一个对象,是Object.entries()的逆操作
console.log(Object.fromEntries(Object.entries(obj))); //{a: 1, b: 2}
// hasOwnProperty():返回一个布尔值,指示对象自身属性中是否具有指定的属性
console.log(obj.hasOwnProperty("a"), obj.hasOwnProperty("c")); //true false
// Object.assign():用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
const t = { a: 1, b: 3 };
const s = { b: 4, c: 5 };
const r = Object.assign(t, s);
console.log(r, t, s); // r:{a: 1, b: 4, c: 5} t:{a: 1, b: 4, c: 5} s:{b: 4, c: 5}
//对象复制
console.log(Object.assign({}, r)); //{a: 1, b: 4, c: 5}
// Object.is() 判断两个变量是否相同
const t1 = { a: 1, b: 3 };
const t2 = { a: 1, b: 3 };
console.log(Object.is(t1, t2), t1 === t2); //false false
const t3 = t1;
console.log(Object.is(t1, t3), t1 === t3); //true true
//判断是否为Object类型
console.log(Object.getPrototypeOf(r) === Object.prototype); //true
console.log(Object.getPrototypeOf([]) === Object.prototype); //false
</script>
其它对象方法
<script>
// Number 对象
const x = 9.656;
// toExponential() 返回字符串值,它包含已被四舍五入并使用指数计数法的数字。参数定义小数点后的字符数
console.log(x.toExponential(2)); //字符串 9.66e+0
// toFixed() 返回字符串值,它包含了指定位数小数的数字
console.log(x.toFixed(2)); //字符串 9.66
// toPrecision() 返回字符串值,它包含了指定长度的数字
console.log(x.toPrecision(2)); //字符串 9.7
// Number():把对象的值转换为数字
console.log(Number("99.00")); //99
console.log(Number(false)); //0
// Math对象
//返回介于0(包含)-1(不包含)之间的一个随机数:
console.log(Math.random());
//round() 方法可把一个数字舍入为最接近的整数:
console.log(Math.round(2.5)); //3
// floor(x) 对 x 进行下舍入
console.log(Math.floor(1.6)); //1
// ceil(x) 对数进行上舍入
console.log(Math.ceil(1.4)); //2
// abs(x) 返回数的绝对值
console.log(Math.abs(-1)); //1
// max(x,y) 返回 x 和 y 中的最大值
console.log(Math.max(2, 5)); //5
// min(x,y) 返回 x 和 y 中的最小值
console.log(Math.min(2, 5)); //2
// pow(x,y) 返回 x 的 y 次幂
console.log(Math.pow(2, 2)); //4
// sqrt(x) 返回数的平方根
console.log(Math.sqrt(4)); //2
// JSON 方法
const obj = { a: 2, b: 3 };
const arr = [2, 3];
// stringify() 将对象转换为字符串
const strObj = JSON.stringify(obj);
const strArr = JSON.stringify(arr);
console.log(strObj, strArr); //字符串 {"a":2,"b":3} [2,3]
// parse() 解析一个json字符串并返回对象
console.log(JSON.parse(strObj), JSON.parse(strArr)); //{a: 2, b: 3} [2, 3]
// RegExp对象
const str = "hello world! Hello";
const pattern = /Hello/gi;
// exec() 检索字符串中指定的值。返回找到的值,并确定其位置。
console.log(pattern.exec(str)); //['Hello', index: 0, input: 'Hello world! Hello', groups: undefined]
// test() 检索字符串中指定的值。返回 true 或 false
console.log(pattern.test(str)); //true
// match()方法在字符串中查找所有匹配,并返回一个数组
console.log(str.match(pattern)); // ['hello', 'Hello']
//全局方法
// encodeURI() 把字符串编码为URI
console.log(encodeURI("http://localhost:3000/1 2.html")); //http://localhost:3000/1%202.html
// decodeURI() 解码某个编码的URI
console.log(decodeURI("http://localhost:3000/1%202.html")); //http://localhost:3000/1 2.html
// escape():对字符串进行编码
const es = escape("?!=()#%&");
console.log(es); //%3F%21%3D%28%29%23%25%26
// unescape():对由escape()编码的字符串进行解码
console.log(unescape(es)); //?!=()#%&
// eval():计算 JavaScript 字符串,并把它作为脚本代码来执行
console.log(eval(3 + 4)); //7
// isNaN():检查某个值是否不是数字
console.log(isNaN("12"), isNaN("1.20"), isNaN("1.20a"), isNaN("a1.20")); //false false true true
// parseFloat():解析一个字符串并返回一个浮点数
console.log(parseFloat("99.00 n")); //99
// parseInt():解析一个字符串并返回一个整数
console.log(parseInt("10")); //10
console.log(parseInt("10", 8)); //将'10'按照8进制转换,结果为8
// String():把对象的值转换为字符串
console.log(String(10)); //字符串10
//判断一个值是否是无穷大
console.log(isFinite(Infinity), isFinite(-Infinity), isFinite(100), isFinite("a")); //false false true false
// Function对象
//将函数作为指定对象的方法来调用,传递给它的是指定的参数数组
const personFunc = {
fullName: function (country) {
return this.name + "," + country;
},
};
const person = {
name: "ming",
};
console.log(personFunc.fullName.apply(person, ["china"])); //ming,china
console.log(personFunc.fullName.call(person, "china")); //ming,china
// 在数组上模拟 max 方法
console.log(Math.max.apply(null, [1, 2, 3]), Math.max.call(null, 1, 2, 3)); // 3 3
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix