返回

JS自用学习笔记(一)

前端

数组属性和方法

数组是一种可以存储多个值的数据结构,在JS中,数组使用方括号([])来表示。数组具有多种属性和方法,可以帮助我们操作和管理数组中的数据。

1. 属性

1.1 length

length属性返回数组中元素的个数。

const arr = [1, 2, 3, 4, 5];
console.log(arr.length); // 输出: 5

1.2 constructor

constructor属性返回创建此数组的函数。

const arr = [1, 2, 3, 4, 5];
console.log(arr.constructor); // 输出: Array

2. 方法

2.1 push()

push()方法向数组的末尾添加一个或多个元素,并返回新的长度。

const arr = [1, 2, 3, 4, 5];
arr.push(6, 7);
console.log(arr); // 输出: [1, 2, 3, 4, 5, 6, 7]

2.2 pop()

pop()方法从数组的末尾删除最后一个元素,并返回该元素。

const arr = [1, 2, 3, 4, 5];
const lastElement = arr.pop();
console.log(lastElement); // 输出: 5
console.log(arr); // 输出: [1, 2, 3, 4]

2.3 shift()

shift()方法从数组的开头删除第一个元素,并返回该元素。

const arr = [1, 2, 3, 4, 5];
const firstElement = arr.shift();
console.log(firstElement); // 输出: 1
console.log(arr); // 输出: [2, 3, 4, 5]

2.4 unshift()

unshift()方法向数组的开头添加一个或多个元素,并返回新的长度。

const arr = [1, 2, 3, 4, 5];
arr.unshift(0);
console.log(arr); // 输出: [0, 1, 2, 3, 4, 5]

对象属性和方法

对象是一种可以存储多个键值对的数据结构,在JS中,对象使用大括号({})来表示。对象具有多种属性和方法,可以帮助我们操作和管理对象中的数据。

1. 属性

1.1 constructor

constructor属性返回创建此对象的函数。

const obj = {
  name: 'John Doe',
  age: 30
};
console.log(obj.constructor); // 输出: Object

2. 方法

2.1 hasOwnProperty()

hasOwnProperty()方法检查对象是否包含指定的属性。

const obj = {
  name: 'John Doe',
  age: 30
};
console.log(obj.hasOwnProperty('name')); // 输出: true
console.log(obj.hasOwnProperty('email')); // 输出: false

2.2 propertyIsEnumerable()

propertyIsEnumerable()方法检查对象的属性是否可枚举。

const obj = {
  name: 'John Doe',
  age: 30
};
console.log(obj.propertyIsEnumerable('name')); // 输出: true
console.log(obj.propertyIsEnumerable('constructor')); // 输出: false

2.3 isPrototypeOf()

isPrototypeOf()方法检查对象是否为另一个对象的原型。

const obj = {
  name: 'John Doe',
  age: 30
};
const newObj = Object.create(obj);
console.log(obj.isPrototypeOf(newObj)); // 输出: true
console.log(Object.prototype.isPrototypeOf(obj)); // 输出: true

2.4 toString()

toString()方法返回对象的字符串表示。

const obj = {
  name: 'John Doe',
  age: 30
};
console.log(obj.toString()); // 输出: "[object Object]"