js中常用的操作方法

数组

push 从数组末尾追加

从数组末尾添加,返回值是数组的长度,会改变原数组

const arr = [1, 2, 3, 4, 5]
console.log(arr.push(6, 7));        // 7 返回值:arr数组的长度 
console.log(arr);                   //输出结果:[1, 2, 3, 4, 5, 6, 7]
unShift 从数组前面添加

从数组前面添加,返回值是数组的长度,会改变原数组

const arr = [1, 2, 3, 4, 5]
console.log(arr.unshift(0));        // 6 返回值:arr数组的长度 
console.log(arr);                   //输出结果:[ 0, 1, 2, 3, 4, 5 ]

pop 从数组末尾删除

从数组末尾删除,返回值是删除的值,会改变原数组

const arr = [1, 2, 3, 4, 5]
console.log(arr.pop());        // 1 删除的值
console.log(arr);              //输出结果:[ 2, 3, 4,5 ]
shift 从数组前面删除

从数组前端删除,返回值是删除的值,会改变原数组

const arr = [1, 2, 3, 4, 5]
console.log(arr.shift());      // 5 删除的值
console.log(arr);              //输出结果:[ 1, 2, 3, 4 ]
splice 删除数组中的元素

删除从index处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素,直接对数组进行修改。

// 根据索引删除元素arr.splice(要删除的内容的下标,删除几个,需要替换的元素) 
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
console.log(arr.splice(0, 2, '123'));     // 返回值是被删除的元素['a','b']  
console.log(arr);          //最终数组 [ '123', 'c', 'd', 'e', 'f', 'g' ]
 
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
console.log(arr.splice(0, 2, '123'));     // 返回值是被删除的元素[]  
console.log(arr);          //最终数组 ['a', 'b', 'c', 'd', 'e', 'f', 'g']

flat

按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。此方法不会改变原数组。

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());        // [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));       // [0, 1, 2, [3, 4]]
map 重新格式化数组

对数组的每一项都运行给定的函数,返回每次函数调用的结果组成一个新数组

const arr = [1, 4, 9, 16];
 
const newArr = arr .map(x => x * 2); 
console.log(newArr);  // 输出结果:[2, 8, 18, 32]
reduce 数组求和

对数组中的每个元素执行指定操作,返回一个累计值。

const arr = [1, 2, 3, 4];

// 接收四个参数,初始值,当前值,当前索引,当前数组对象
const sum = arr.reduce(function(prev, cur, index, arr) {
    return prev + cur;
})
console.log(sum); // 10
jion 数组转换为字符串

用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的,默认使用’,'号分割,不改变原数组。

const arr = ['a','b','c','d'];
const str = arr.join("-")   // 输出结果为: "a-b-c-d"
concat 拼接数组

用来拼接数组 并且 会返回一个新数组。该方法不会改变原数组

const arr = [1, 2, 3, 4, 5, 6];
console.log(arr.concat([7, 8, 9]));
//输出结果:[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
 
const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [7, 8, 9]
const arr3 = arr1.concat(arr2)
console.log(arr1);      //[ 1, 2, 3, 4, 5, 6 ]
console.log(arr3);      //输出结果:[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
reverse 反转数组

用于颠倒数组中元素的顺序。返回的是颠倒后的数组,会改变原数组

const arr = [1, 2, 3, 4, 5]
console.log(arr.reverse());        // 输出结果  [ 5, 4, 3, 2, 1 ]
sort 排序 数组排序

对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序,会改变原数组。

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);   // ["Dec", "Feb", "Jan", "March"]
 
const arr = [1, 30, 4, 21, 100000];
array1.sort();
console.log(arr);      // [1, 100000, 21, 30, 4]

find 数组中满足第一个条件元素

返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

// 获取数组中第一个大于10的值
const arr= [5, 12, 8, 130, 44];

const found = arr.find(item=> item > 10);
console.log(found);  // 输出结果:12
findIndex 数组中满足第一个条件元素下标

方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1

const arr= [5, 12, 8, 130, 44];
console.log(arr.findIndex((item) => item> 13;));   // 输出结果:3
include 检测数组是否包含指定元素

检测数组是否包含指定元素,如果存在则返回 true,否则返回 false

const arr = [1, 2, 3, 4, 5];

console.log(arr.includes(3)) // 输出结果:true
console.log(arr.includes(99)) // 输出结果:false
some 判断数组中是否有满足( 其中一个 )

some方法和every方法非常的类似 ,所有元素遍历之后,所有元素都满足条件的元素是返回值为true,若有一个不满足则返回false

const arr = [1, 2, 3, 4, 5, 6]
console.log(arr.some(item => item > 6));     //输出结果:false
console.log(arr.some(item => item > 3));     //输出结果:true
every 判断数组中是否有满足( 所有 )

 一般用于判断数组中是否有满足条件的数组元素,所有元素遍历之后,所有元素都满足条件的元素是返回值为true,若有一个不满足则返回false

const arr = [1, 2, 3, 4, 5, 6]
console.log(arr.every(item => item > 1));     //输出结果:false 
console.log(arr.every(item => item > 0));     //输出结果:true
indexof 检测当前值在数组中第一次出现的位置索引

返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

const arr = ['ant', 'bison', 'camel', 'duck', 'bison'];
 
console.log(arr.indexOf('bison'));     // 1 
// 从下标为2的开始查找
console.log(arr.indexOf('bison', 2));  // 4
console.log(arr.indexOf('giraffe'));   // -1

过滤

filter 过滤数组

filter返回值是一个新的数组,filter里面可以直接 return 筛选条件 

const arr = [20, 50, 80]
/* 
   item:数组每一项
   index:数组每一项的x下标
   array:数组本身
*/
const newArr = arr.filter((item, index, array) => {
    return item >= 70
})
console.log(newArr);  
//返回筛选后的数组 [ 80 ]

循环

foreach 循环遍历

用于循环遍历数组最常用的方法之一,它提供一个回调函数,可用于处理数组的每一个元素,默认没有返回值。回调函数的参数,第一个参数是数组的每一项,第二个参数是数组中每一项的下标 

const arr = [1, 2, 3, 4, 5, 6];

arr.forEach((item, index) => {
    console.log(item);
    console.log(index);
});

//输出结果:item : 1 2 3 4 5 6 , index: 0 1 2 3 4 5

对象

Object.keys 遍历可枚举的属性

let arr = ["a", "b", "c"];
let obj = { foo: "bar", baz: 42 };
let ArrayLike = { 0 : "a", 1 : "b", 2 : "c"};

Object.keys(arr)        // ['0', '1', '2']
Object.keys(obj)        // ["foo","baz"]
Object.keys(ArrayLike)  // ['0', '1', '2']

Object.values 遍历可枚举的属性值

let arr = ["a", "b", "c"];
let obj = { foo: "bar", baz: 42 };
let ArrayLike = { 0 : "a", 1 : "b", 2 : "c"};

Object.values(arr)      // ["a", "b", "c"]
Object.values(obj)          // ["bar",42]
Object.values(ArrayLike)    // ["a", "b", "c"]

Object.assign 对象的合并

如果目标对象和源对象有同名属性,或多个源对象有同名属性,后面的属性会覆盖前面的属性。
如果只有一个参数,Object.assign会直接返回该参数。

const source1 = { a: 1, b: 2 };
const source2 = { b: 3, a: 4 };
Object.assign(source1, source2); // { a: 4, b: 3}

const obj = {a: 1};  
Object.assign(obj) === obj //  true  

Object.create 创建对象

Object.entries 将对象转化为数组

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

//  string
Object.entries('abc')   // [['0', 'a'], ['1', 'b'], ['2', 'c']]

Object.entries(100)   // []

Object.defineProperty 修改已有的对象属性或者添加属性

const obj2 = {};
Object.defineProperty(obj2, 'c', {
	get() {
		return obj2['c'];
	},
	set(newVal) {
		obj2['c'] = newVal;
	},
});
obj.c = 2;
console.log(obj2.c);

Object.hasOwnProperty 对象自身属性中是否具有指定的属性

console.log(obj.hasOwnProperty('a')); //true
console.log(obj.hasOwnProperty('e')); //false
Object.setPrototypeOf(obj, { c: 3 }); // 设置原型属性
console.log(obj.hasOwnProperty('c')); // false

Object.setPrototypeOf 设置指定对象的原型

Object.getPrototypeOf 获取指定对象的原型

const obj = {
	a:1,
	b:3
}

// 设置原型
Object.setPrototypeOf(obj,{c:7});
console.log(obj);  // {a: 1, b: 3}  [[Prototype]]: c: 7

// 以下 3 种方式都获取到了 obj 的原型,但是只有第一种是函数式方法,是 js 内置提供的方法,推荐使用第一种
console.log(Object.getPrototypeOf(obj));
console.log(obj.__proto__);
console.log(Object.prototype);

字符串

padEnt && padStart 补齐字符串长度

该方法也是接收两个参数,第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串

'x'.padStart(1, 'ab') // 'x'
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padStart(4) // '   x'

"1".padStart(3, '0')   // 输出结果: '001'
"15".padStart(3, '0')  // 输出结果: '015'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

slice

用于提取字符串的某个部分,并以新的字符串返回被提取的部分。

 start:必须。 要截取的片断的起始下标,第一个字符位置为 0。如果为负数,则从尾部开始截取。

 end:可选。 要截取的片段结尾的下标。若未指定此参数,则要提取的子串包括

const str = "abcdefg";
str.slice(1,6);   // 输出结果:"bcdef" 
str.slice(1);     // 输出结果:"bcdefg" 
str.slice();      // 输出结果:"abcdefg" 
str.slice(-2);    // 输出结果:"fg"
str.slice(6, 1);  // 输出结果:""
subString

用于提取字符串中介于两个指定下标之间的字符。

 from:必需。一个非负的整数,规定要提取的子串的第一个字符在 string 中的位置。

 to:可选。一个非负的整数,比要提取的子串的最后一个字符在 string 中的位置多 1。如果省略该参数,那么返回的子串会一直到字符串的结尾。

const str = "abcdefg";
str.substring(1,6); // 输出结果:"bcdef" [1,6)
str.substring(1);   // 输出结果:"bcdefg" [1,str.length-1]
str.substring();    // 输出结果:"abcdefg" [0,str.length-1]
str.substring(6,1); // 输出结果 "bcdef" [1,6)
str.substring(-1);  // 输出结果:"abcdefg"

subStr

用于在字符串中抽取从开始下标开始的指定数目的字符。

start 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
length:可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。

const str = "abcdefg";
str.substr(1,6); // 输出结果:"bcdefg" 
str.substr(1);   // 输出结果:"bcdefg" 相当于截取[1,str.length-1]
str.substr();    // 输出结果:"abcdefg" 相当于截取[0,str.length-1]
str.substr(-1);  // 输出结果:"g"
trim 移除字符串首尾空白符
let str = "  abcdef  "
str.trim()    // 输出结果:"abcdef"

trimStart 从原始字符串的开头删除了空白的新字符串,不会修改原始字符串

const s = '  abc  ';
s.trimStart()   // "abc  "

trimEnd 从原始字符串的结尾删除了空白的新字符串,不会修改原始字符串

const s = '  abc  ';
s.trimEnd()   // "  abc"

repeat 重复一个字符串
'x'.repeat(3)     // 输出结果:"xxx"
'hello'.repeat(2) // 输出结果:"hellohello"
'na'.repeat(0)    // 输出结果:""
split 分割字符串

用于把一个字符串分割成字符串数组。该方法不会改变原始字符串。

let str = "abcdef";
str.split("c");    // 输出结果:["ab", "def"]
str.split("", 4)   // 输出结果:['a', 'b', 'c', 'd'] 
concat 连接多个字符串

用于连接两个或多个字符串。该方法不会改变原有字符串,会返回连接两个或多个字符串的新字符串。

let str = "abc";
console.log(str.concat("efg"));          //输出结果:"abcefg"
console.log(str.concat("efg","hijk")); //输出结果:"abcefghijk"
toLowerCase && toUpperCase 转换大小写

字符串转换为小写:

let str = "adABDndj";
str.toLowerCase(); // 输出结果:"adabdndj"

字符串转换为大写:

let str = "adABDndj";
str.toUpperCase(); // 输出结果:"ADABDNDJ"

将字符串中第一个字母变成大写: 

let word = 'apple'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // 输出结果:"Apple"
replace 替换字符串

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串;返回指定的值,而不是字符串的位置。

let str = "abcdef";
str.replace("c", "z") // 输出结果:abzdef

// 全局替换, 忽略大小写
let str="Mr Blue has a blue house and a blue car";
str.replace(/blue/gi, "red");    // 输出结果:'Mr red has a red house and a red car'
match 

用于在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

let str = "abcdef";
console.log(str.match("c")) // ["c", index: 2, input: "abcdef", groups: undefined]
search

用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。

let str = "abcdef";
str.search(/bcd/)   // 输出结果:1
parseFloat 字符串转为数字
parseFloat("10.00")      // 输出结果:10.00
parseFloat("10.01")      // 输出结果:10.01
parseFloat("-10.01")     // 输出结果:-10.01
parseFloat("40.5 years") // 输出结果:40.5

parseFloat("new40.5")    // 输出结果:NaN

length 获取字符串长度
const str = "hello",
str.length
indexOf 检索字符串是否包含
let str = "abcdefgabc";
console.log(str.indexOf("a"));   // 输出结果:0
console.log(str.indexOf("z"));   // 输出结果:-1
console.log(str.indexOf("c", 4)) // 输出结果:9
charAt 获取字符串指定位置的值
const str = 'hello';
str.charAt(1)  // 输出结果:e 
str[1]         // 输出结果:e 
str.charAt(5)  // 输出结果:'' 
str[5]         // 输出结果:undefined
includes 判断字符串是否包含指定的子字符串

如果找到匹配的字符串则返回 true,否则返回 false。

let str = 'Hello world!';
str.includes('o')  // 输出结果:true
str.includes('z')  // 输出结果:false
str.includes('e', 2)  // 输出结果:false
ebdsWith && startsWith 是否以指定的子字符串开始/结束

如果是以指定的子字符串开头返回 true,否则 false。

let str = 'Hello world!';
str.startsWith('Hello') // 输出结果:true
str.startsWith('Helle') // 输出结果:false
str.startsWith('wo', 6) // 输出结果:true
let str = 'Hello world!';

str.endsWith('!')       // 输出结果:true
str.endsWith('llo')     // 输出结果:false
str.endsWith('llo', 5)  // 输出结果:true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值