一、JSON
stringify(object)
: 将object
对象转换为JSON
字符串,并返回该字符串。
parse(string)
: 将JSON
字符串转化成对象,并返回该对象。
//stringify;将对象转换为 JSON 字符串
const userInfo = {
name: 'zs',
age: 20
}
console.log(JSON.stringify(userInfo));
//parse:将JSON 字符串转化成对象
var jstr = '{"name":"wust", "url":"www.wust.edu.cn", "age":120}'
var obj = JSON.parse(jstr);
console.log(obj);
二、数组
① ...
扩展运算符(spread)是三个点(
...
),将一个数组转为用逗号分隔的参数序列。
var obj = { "message": "success", "data": ["43, 29, 75", "159, 33, 106"] }
var a = [obj, 2, '5', true]
console.log(a);
console.log(...a);
② splice
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
注释:该方法会改变原始数组。
splice | 功能 | 函数 | 参数说明 | 返回值 | |
删除 | splice(index, howmany) | 第一个参数:index | 删除的数据的起始位置 | 删除的内容 | |
第二个参数:howmany | 删除的数据个数。 | ||||
替换 | splice(index, howmany, item1, item2, ..., itemn) | 第一类参数:index | 删除的数据的起始位置 | 替换的内容 | |
第二类参数:howmany | 删除的数据个数 | ||||
第三类参数:(item1, item2, ..., itemn) | 替换的数据(可以理解为先删除,后替换) | ||||
插入 | splice(index, 0, item1, item2, ..., itemn) | 第一类参数:index | 插入的位置 | 空数组 | |
第二类参数:0 | 必须为0(表示函数执行插入功能) | ||||
第三类参数:(item1, item2, ..., itemn) | 插入的数据 |
删除: 在数组[1, 3, 5, 8, 19, 10]中,需要删除3,5,8这三个数字。
let nums = [1, 3, 5, 8, 19, 10]
nums.splice(1, 3)
注:数字1指的是从下标为1的数字开始删除, 删除3个数字,即3,5,8。
替换: 在数组[1, 3, 5, 8, 19, 10]中,需要将这3,5,8三个数字替换成2,4,8。
let nums = [1, 3, 5, 8, 19, 10]
nums.splice(1, 3, 2, 4, 8)
注:可以理解为先删除3,5,8这三个数据,之后再添加替换2,4,8三个数据。
插入:在数组[1, 3, 5, 8, 19, 10]中,在5后面插入a、b、c三个字符。
let nums = [1, 3, 5, 8, 19, 10]
nums.splice(3, 0, 'a', 'b', 'c')
③ find 和 findIndex
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
find() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。
注意: find() 并没有改变数组的原始值。
语法: arr.find(callback[, thisArg])
arr.findIndex(callback[, thisArg])
find
// 例、find()方法 查找数组中第一个大于等于15的元素
var num = [10, 3, 5, 15, 100, 1]
var a = num.find(function (elem, index) {
return elem >= 15;
});
// 箭头函数 var a = num.find(e => e >= 15);
console.log(num)
console.log(a);
findIndex
// 例二、findIndex() 查找数组中第一个大于等于15的元素的位置(索引)
var num = [10, 3, 5, 15, 100, 1]
var b = num.findIndex(function (elem, index) { // 15
return elem >= 15;
});
// var a = num.findIndex(e => e >= 15);
console.log(num)
console.log(b);
三、字符串
① replace
replace()
方法返回一个由替换值(replacement
)替换部分或所有的模式(pattern
)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern
是字符串,则仅替换第一个匹配项。
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
//第一个参数是字符串,只能替换一个
console.log(p.replace('dog', 'monkey'));
//第一个参数是正则表达式/g,替换所有
const regex = /dog/g;
console.log(p.replace(regex, 'ferret'));
② slice
slice()
方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
console.log(str.slice(-4));
// expected output: "dog."
console.log(str.slice(-9, -5));
// expected output: "lazy"