如果你是一名前端工作者,css和js的学习就显得尤为重要。此篇文章用来解决对JS类型的操作。当涉及到字符、对象和数组的方法时,有很多内置的JavaScript方法可以用来解决问题。下面是一些常用的方法和示例:
字符串方法:
一: length:获取字符串的长度。
const str = 'Hello World';
console.log(str.length);
// 输出: 11
二:toUpperCase():将字符串转换为大写。
const str = 'Hello World';
console.log(str.toUpperCase());
// 输出: 'HELLO WORLD'
三:trim():去除字符串两端的空格。
" hello ".trim() // 输出:'hello'
四:split(separator):将字符串分割成一个字符串数组。
const str = 'Hello,World,JavaScript';
console.log(str.split(','));
// 输出: ['Hello', 'World', 'JavaScript']
五:concat(str1, str2, … , strN): 连接两个或多个字符串。
var str1 = "Hello";
var str2 = "World";
console.log(str1.concat(" ", str2));
// 输出 "Hello World"
六:concat(str1, str2, … , strN): 截取字符串。
var str1 = "Hello World";
console.log(str1.substring(0,1);
// 输出 "H"
console.log(str1.lastIndexOf(" ") + 1,5); //截取最后一个点号后5个字符
// 输出 "World"
对象方法:
一:hasOwnProperty(property):检查对象是否具有指定的属性。
const obj = { a: 1, b: 2 };
console.log(obj.hasOwnProperty('a'));
// 输出: true
console.log(obj.hasOwnProperty('c'));
// 输出: false
二:keys():获取对象的所有键,返回一个由对象的属性名组成的数组
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));
// 输出: ['a', 'b', 'c']
三:values():获取对象的所有值,返回一个由对象的属性值组成的数组。
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));
// 输出: [1, 2, 3]
四:assign( target, source1, source2, …):将源对象的属性复制到目标对象。
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
Object.assign(target, source);
console.log(target);
// 输出: { a: 1, b: 3, c: 4 }
数组方法:
一: length:获取数组的长度。
const arr = [1, 2, 3, 4, 5];
console.log(arr.length);
// 输出: 5
二: push(element):向数组末尾添加一个元素。
const arr = [1, 2, 3];
arr.push(4);
console.log(arr);
// 输出: [1, 2, 3, 4]
三:pop():移除并返回数组末尾的元素。
const arr = [1, 2, 3];
const removedElement = arr.pop();
console.log(removedElement);
// 输出: 3
console.log(arr);
// 输出: [1, 2]
四:indexOf(element):返回数组中第一个匹配元素的索引。
const arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(3));
// 输出: 2
五:splice(start, deleteCount, element1, …, elementN):从指定位置删除或替换元素。
const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 'a', 'b');
console.log(arr);
// 输出: [1, 2, 'a', 'b', 4, 5]
六:for:遍历数组。
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//输出 1
//输出 2
//输出 3
//输出 4
//输出 5
七:for…of循环:遍历数组。
const arr = [1, 2, 3, 4, 5];
for (const element of arr) {
console.log(element);
}
//输出 1
//输出 2
//输出 3
//输出 4
//输出 5
八:forEach:对数组中的每个元素执行一个回调函数(遍历数组)。
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number);
});
//输出 1
//输出 2
//输出 3
//输出 4
//输出 5
九:map:使用回调函数对数组中的每个元素进行处理,然后返回一个新的数组(遍历数组)。
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => {
return number * 2;
});
console.log(doubledNumbers);
//输出 [2, 4, 6, 8, 10]
十:filter:使用回调函数对数组中的每个元素进行测试,并返回一个由通过测试的元素组成的新数组(遍历数组)。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});
console.log(evenNumbers);
//输出 [2,4]
十一:reduce:逐个遍历数组元素,每一步都将当前元素的值与前一步的结果相加。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum);
// 输出: 15(原理:1+2+3+4+5)
十二:some:方法将检查数组中是否存在至少一个符合条件的元素。
const ages = [16, 22, 19, 25, 30];
const isAdultPresent = ages.some((age) => {
return age >= 18;
});
console.log(isAdultPresent);
// 输出: true
十三:every:方法将检查数组中的所有元素是否都符合条件。
const ages = [16, 22, 19, 25, 30];
const isAllPassed = ages .every((age) => {
return age>= 10;
});
console.log(isAllPassed);
// 输出: true
以上是一些类型的基本操作,当然,对于他们的操作还有很多,可以访问MDN官网进行详细的学习(https://developer.mozilla.org/zh-CN/)。
下边是对各类型之间的转换操作,在实际工作中也是应用广泛!
一:JSON.parse():将符合 JSON 格式的字符串转换为对象。(字符串->对象)
const jsonStr = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonStr);
console.log(obj);
// { name: 'Alice', age: 25 }
二:JSON.stringify():将对象转换为 JSON 格式的字符串。(对象->字符串)
const obj = { name: 'Alice', age: 25 };
const jsonStr = JSON.stringify(obj);
console.log(jsonStr);
// '{"name":"Alice","age":25}'
三:split():按指定的分隔符将字符串拆分为数组的多个元素。(字符串->数组)。
const str = 'apple,banana,orange';
const arr = str.split(',');
console.log(arr);
// ['apple', 'banana', 'orange']
四:join():将数组的每个元素用指定的分隔符连接成一个字符串。(数组->字符串)
const arr = ['apple', 'banana', 'orange'];
const str = arr.join(',');
console.log(str);
// 'apple,banana,orange'
五:forEach:遍历数组,并将每个元素添加到一个新对象中。(数组->对象)
const arr = ['name', 'age', 'gender'];
const obj = {};
arr.forEach((item) => {
obj[item] = '';
});
console.log(obj); // { name: '', age: '', gender: '' }
六:map:遍历数组,并将每个元素添加到一个新对象中。(数组->对象)
const obj = { name: 'John', age: 30, gender: 'male' };
const arr = Object.keys(obj).map((key) => key);
console.log(arr);
// ['name', 'age', 'gender']
以上是各类型之间的转换方法,下边是判断数据类型。只有我们知道了数据的类型,才可以对症下药,使用具体的方法
一:typeof:用来确定一个值的基本类型,返回一个表示数据类型的字符串。
typeof "Hello" // 返回 "string"
typeof true // 返回 "boolean"
typeof 42 // 返回 "number"
typeof undefined // 返回 "undefined"
typeof null // 返回 "object" (这是一个历史遗留问题,null 被错误地判断为 "object" 类型)
typeof [] // 返回 "object"
typeof {} // 返回 "object"
typeof new Date() // 返回 "object"
typeof function() {} // 返回 "function"
二:instanceof :用来检查实例是否属于某个构造函数。
"Hello" instanceof String // 返回 false("string" 是原始类型而非对象)
new String("Hello") instanceof String // 返回 true(String 是构造函数,通过 new 关键字创建的实例属于 String 类型)
[] instanceof Array // 返回 true
{} instanceof Object // 返回 true
new Date() instanceof Date // 返回 true
(function() {}) instanceof Function // 返回 true
三:Object.prototype.toString.call():返回内部属性,从而判断对象的详细类型。
Object.prototype.toString.call("Hello") // 返回 "[object String]"
Object.prototype.toString.call(true) // 返回 "[object Boolean]"
Object.prototype.toString.call(42) // 返回 "[object Number]"
Object.prototype.toString.call(undefined) // 返回 "[object Undefined]"
Object.prototype.toString.call(null) // 返回 "[object Null]"
Object.prototype.toString.call([]) // 返回 "[object Array]"
Object.prototype.toString.call({}) // 返回 "[object Object]"
Object.prototype.toString.call(new Date()) // 返回 "[object Date]"
Object.prototype.toString.call(function() {}) // 返回 "[object Function]"
好啦,就总结这么多,掌握了这些,在项目开发过程中就可以应对98%的问题了,要勤加练习,以后不用翻博客笔记也可以记得住!最后,如果这篇文章帮到了你,或者说以后用得到,记得点赞收藏哟!欢迎大家留言…