📜  javascript中的对象方法(1)

📅  最后修改于: 2023-12-03 15:16:17.213000             🧑  作者: Mango

JavaScript中的对象方法

JavaScript中的对象是由属性和方法组成的,方法是一种函数,可以更改对象的属性或做一些其他的操作。这篇文章会介绍一些常用的对象方法。

Object

Object是所有对象的祖先,所有对象都从Object继承了一些方法。

Object.keys(obj)

这个方法返回一个数组,包含对象所有可枚举的属性的名称。

const obj = {a: 1, b: 2, c: 3};
const keys = Object.keys(obj);
console.log(keys); // ["a", "b", "c"]
Object.values(obj)

这个方法返回一个数组,包含对象所有可枚举的属性的值。

const obj = {a: 1, b: 2, c: 3};
const values = Object.values(obj);
console.log(values); // [1, 2, 3]
Object.entries(obj)

这个方法返回一个数组,包含对象所有可枚举的属性的名称和值的二元组数组。

const obj = {a: 1, b: 2, c: 3};
const entries = Object.entries(obj);
console.log(entries); // [["a", 1], ["b", 2], ["c", 3]]
Array

Array是一种特殊的对象,其对象的属性被定义为从0开始的数字索引。

Array.prototype.push(...items)

这个方法将一个或多个元素添加到数组的末尾,并返回新的长度。

const arr = [1, 2];
const newLength = arr.push(3, 4);
console.log(arr); // [1, 2, 3, 4]
console.log(newLength); // 4
Array.prototype.pop()

这个方法删除数组的最后一个元素,并返回该元素的值。

const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(arr); // [1, 2]
console.log(lastElement); // 3
Array.prototype.shift()

这个方法删除数组的第一个元素,并返回该元素的值。

const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(arr); // [2, 3]
console.log(firstElement); // 1
Array.prototype.unshift(...items)

这个方法将一个或多个元素添加到数组的开头,并返回新的长度。

const arr = [2, 3];
const newLength = arr.unshift(0, 1);
console.log(arr); // [0, 1, 2, 3]
console.log(newLength); // 4
Array.prototype.slice(startIndex, endIndex)

这个方法返回一个新的数组,从startIndex开始,到endIndex-1结束。

const arr = [0, 1, 2, 3, 4];
const slicedArr = arr.slice(1, 4);
console.log(slicedArr); // [1, 2, 3]
String

String是一种特殊的对象,其对象的属性被定义为从0开始的数字索引。String也有一些方法可以操作字符串。

String.prototype.concat(...strings)

这个方法将两个或多个字符串连接起来,并返回一个新的字符串。

const str1 = 'hello';
const str2 = 'world';
const str3 = str1.concat(' ', str2);
console.log(str3); // "hello world"
String.prototype.indexOf(searchValue, fromIndex)

这个方法返回第一个出现searchValue的位置的索引,如果没有找到,返回-1。fromIndex是可选参数,可以指定从哪个索引开始搜索。

const str = 'hello, world';
const index = str.indexOf('world');
console.log(index); // 7
String.prototype.lastIndexOf(searchValue, fromIndex)

这个方法返回最后一个出现searchValue的位置的索引,如果没有找到,返回-1。fromIndex是可选参数,可以指定从哪个索引开始搜索。

const str = 'hello, world';
const index = str.lastIndexOf('o');
console.log(index); // 8
String.prototype.split(separator, limit)

这个方法将字符串分割成数组,并返回新的数组。separator是分隔符,可以是字符串,也可以是正则表达式。limit是可选参数,指定返回的数组的最大长度。

const str = 'a,b,c';
const arr1 = str.split(',');
console.log(arr1); // ["a", "b", "c"]

const arr2 = str.split(',', 2);
console.log(arr2); // ["a", "b"]
Conclusion

这篇文章介绍了常用的JavaScript对象方法,包括Object、Array和String对象的方法。当我们使用JavaScript编写代码时,这些方法可以帮助我们更方便、更高效地操作对象。