返回
剖析常用 JavaScript 方法,轻松掌控前端开发
前端
2024-02-02 04:00:43
JavaScript 作为前端开发的必备利器,拥有丰富的内置方法,能够高效处理各种数据和操作。本文将精选部分常用的 JavaScript 方法进行详细剖析,帮助你深入理解其底层原理和应用场景。
数据类型判定
typeof(value)
该方法可以返回一个值的数据类型。例如:
typeof(1) // "number"
typeof("hello") // "string"
typeof(true) // "boolean"
typeof(null) // "object"
数组去重
Array.from(new Set(array))
利用 Set 的特性,可以轻松去除数组中的重复元素。
const array = [1, 2, 3, 2, 4, 5, 1];
const uniqueArray = Array.from(new Set(array));
console.log(uniqueArray); // [1, 2, 3, 4, 5]
字符串去重
[...new Set(string)].join("")
类似于数组去重,利用 Set 可以轻松去除字符串中的重复字符。
const string = "hello world";
const uniqueString = [...new Set(string)].join("");
console.log(uniqueString); // "helo wrd"
深拷贝浅拷贝
深拷贝
JSON.parse(JSON.stringify(object))
这种方法可以实现对象内容的深度复制,即新对象和原对象完全独立,修改新对象不会影响原对象。
const object1 = {
name: "John",
age: 30,
address: {
street: "123 Main Street",
city: "New York",
state: "NY",
},
};
const object2 = JSON.parse(JSON.stringify(object1));
object2.name = "Mary";
object2.address.street = "456 Elm Street";
console.log(object1); // { name: 'John', age: 30, address: { street: '123 Main Street', city: 'New York', state: 'NY' } }
console.log(object2); // { name: 'Mary', age: 30, address: { street: '456 Elm Street', city: 'New York', state: 'NY' } }
浅拷贝
Object.assign({}, object)
这种方法可以实现对象内容的浅度复制,即新对象和原对象共享相同的引用,修改新对象也会影响原对象。
const object1 = {
name: "John",
age: 30,
address: {
street: "123 Main Street",
city: "New York",
state: "NY",
},
};
const object2 = Object.assign({}, object1);
object2.name = "Mary";
object2.address.street = "456 Elm Street";
console.log(object1); // { name: 'Mary', age: 30, address: { street: '456 Elm Street', city: 'New York', state: 'NY' } }
console.log(object2); // { name: 'Mary', age: 30, address: { street: '456 Elm Street', city: 'New York', state: 'NY' } }