js常用的数据处理方法

发布时间 2024-01-03 16:33:54作者: 珞珞9527

js常用的数据处理方法:

一、数据类型判断

1、typeof

右侧跟一个一元表达式。返回该表达式的数据类型,返回的结果是用该类型的字符串形式表示

number、boolean、symbol、string、object、undefined、function

对于基本类型,除 null 以外,均可以返回正确的结果。

对于引用类型,除 function 以外,一律返回 object 类型。

typeof 2; // number 
typeof undefined; // undefined 
typeof '222'; // string 
typeof true; // boolean
typeof Symbol(); // symbol 
typeof 1n; // bigint
typeof BigInt('1'); // bigint
typeof null; // object 
typeof {}; // object 
typeof []; // object 
typeof new Function(); // function
typeof new Date(); // object
typeof new RegExp(); // object

2、instanceof

当 A 的 __ proto __指向 B 的 prototype 时,就认为 A 就是 B 的实例

instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。

3、constructor

构造函数

null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断

函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object

4、toString

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx],其中 Xxx 就是对象的类型。

对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(Symbol()); // [object Symbol]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(newFunction()); // [object Function]
Object.prototype.toString.call(newDate())=; // [object Date]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(newRegExp()); // [object RegExp]
Object.prototype.toString.call(newError()); // [object Error]

二、常用数组遍历方法

1、forEach()遍历数组

forEach中可以使用return来实现continue的效果

let arr = [1,2,3,4,5,6,8,7,90,78,56,67]
let arr1
arr.forEach(item=>{
    if(item>3&&item<90){
     arr1.push(item)   
}
    return arr1
})

2、every(fn)判断数组中是否所有元素都满足fn函数中的条件

let a = [1, 2, 3, 4, 5];
let result = a.every((currentValue)=>{
    return currentValue > 0;
});
console.log(result);   // true  所有元素都大于0

result = a.every((currentValue)=>{
    return currentValue > 1;
});
console.log(result);   // false  1并不大于1
console.log(a);        // [1, 2, 3, 4, 5]

3、filter(fn)返回数组中满足fn函数中条件的集合

let a = [1, 2, 3, 4, 5];
let result = a.filter((currentValue)=>{
    return currentValue > 4;
});
console.log(result); // [5] 只有5满足条件
console.log(a); // [1, 2, 3, 4, 5]

4.find(fn)返回数组中第一个匹配fn函数中条件的值,没有则返回undefined

let a = [1, 2, 3, 4, 5];
let result = a.find((currentValue)=>{
    return currentValue > 3;
});
console.log(result); // 4

result = a.find((currentValue)=>{
    return currentValue > 5;
})
console.log(result); // undefined
console.log(a); // [1, 2, 3, 4, 5]

5、findIndex(fn)返回数组中第一个匹配fn函数中条件的索引,没有则返回-1

let a = [1, 2, 3, 4, 5];
let result = a.findIndex((currentValue)=>{
    return currentValue > 3;
});

console.log(result);   // 3
result = a.findIndex((currentValue)=>{
    return currentValue > 5;
});
console.log(result); // -1
console.log(a); // [1, 2, 3, 4, 5]

6、includes()返回一个布尔值,表示某个数组是否包含给定的值

let a = [1, 2, 3, 4, 5];
let result = a.includes(2);
console.log(result);   // true

result = a.includes(6);
console.log(result);   // false
console.log(a);        // [1, 2, 3, 4, 5]

7、map(fn)以fn函数中返回值组成新的数组返回

let a = [1, 2, 3, 4, 5];
let result = a.map((v, i)=>{
    return 9;
});
console.log(result);   // [9, 9, 9, 9, 9]
console.log(a);        // [1, 2, 3, 4, 5]

8、reduce()累计器

let a = [1, 2, 3, 4, 5];
let result = a.reduce((accumulator, currentValue, currentIndex, array)=>{
    console.log(accumulator, currentValue, currentIndex, array);
    return accumulator + currentValue;
    // 5  1 0 [1, 2, 3, 4, 5]  第一次accumulator的值为reduce第二个参数5, currentValue为数组第一个元素
    // 6  2 1 [1, 2, 3, 4, 5]  第二次accumulator的值为5加上数组a中的第一个值,即是第一次循环时return的值
    // 8  3 2 [1, 2, 3, 4, 5]  同上
    // 11 4 3 [1, 2, 3, 4, 5]  同上
    // 15 5 4 [1, 2, 3, 4, 5]  同上
}, 5);
console.log(result);   // 20 为最终累计的和

// 无初始值时,accumulator的初始值为数组的第一个元素,currentValue为数组第二个元素
result = a.reduce((accumulator, currentValue, currentIndex, array)=>{
    console.log(accumulator, currentValue, currentIndex, array);
    return accumulator + currentValue;
    // 1  2 1 [1, 2, 3, 4, 5]
    // 3  3 2 [1, 2, 3, 4, 5]
    // 6  4 3 [1, 2, 3, 4, 5]
    // 10 5 4 [1, 2, 3, 4, 5]
})
console.log(result);   // 15 为最终累计的和
console.log(a);        // [1, 2, 3, 4, 5]

9、some(fn)检查数组中是否含有满足fn函数条件的值

let a = [1, 2, 3, 4, 5];
let result = a.some((currentValue)=>{
    return currentValue > 2;
});
console.log(result);   // true

result = a.some((currentValue)=>{
    return currentValue > 6;
});
console.log(result);   // false
console.log(a);        // [1, 2, 3, 4, 5]

三、常用对象遍历方法

1、for-in

let obj = { decrement_fee: "减量",
            increment_fee: "增量",
            manual_fee: "手动",
            online_fee: "线上收入",
            qibin_fee: "奇兵业绩",
            refund_fee: "退款",
            regression_fee: "退差",
            retrieve_fee: "挽回",
            screenshot_fee: "截图业绩",
            special_fee: "特殊业绩",
            total_fee: "业绩"}
 const objArr = []
 for (const key in obj) {
    if (key !== 'decrement_fee' && key !== 'increment_fee') {
        objArr.push({
          label: data[key],
          value: key
        })
      }
    }
    return objArr     //[{
label:'手动',
    value:'manual_fee'
},{
label:'线上收入',
    value:'online_fee'
},
    {
label:'奇兵业绩',
    value:'qibin_fee'
},
    {
label:'退款',
    value:'refund_fee'
},
    {
label:'退差',
    value:'regression_fee'
},
    {
label:'挽回',
    value:'retrieve_fee'
},
    {
label:'截图业绩',
    value:'screenshot_fee'
},{
label:'特殊业绩',
    value:'special_fee'
},{
label:'业绩',
    value:'total_fee'
},
    ]

2、Object.keys(obj)、Object.values(obj)

该方法返回对象自身属性名、属性值组成的数组,它会自动过滤掉原型链上的属性,然后可以通过数组的 forEach() 方法来遍历

let obj = {
    id: 1,
    name: "zhangsan",
    age: 18
};
console.log(Object.keys(obj));    //返回键名组成的数组
// 输出结果: obj对象的key组成的数组['id','name','age']

console.log(Object.values(obj));   //返回键值组成的数组
 // 输出结果: obj对象的value组成的数组['1','zhangsan','18']

Object.keys(obj).forEach((key)=>{
    console.log(key+ '---'+obj[key]);
});
// 输出结果:
// id---1
// name---zhangsan
// age---18

3、Object.getOwnPropertyNames(obj)

该方法返回对象自身属性名组成的数组,包括不可枚举的属性

let obj = {
    id: 1,
    name: "zhangsan",
    age: 18
};
Object.getOwnPropertyNames(obj).forEach((key)=>{
    console.log(key+ '---'+obj[key]);
});
// 输出结果:
// id---1
// name---zhangsan
// age---18

四、常用字符串操作方法

1、charAt()

返回给定位置的那个字符

var stringValue = 'hello world';
console.log(stringValue.charAt(1)); // 'e'

2、concat()

将一或多个字符串拼接起来,返回拼接得到的新的字符串

var stringValue = 'hello ';
var resrult = stringValue.concat('world');
console.log(resrult); // 'hello world'
console.log(stringValue); // 'hello ' 不改变源字符串

3、replace()、replaceAll()

replace()默认替换第一个字符串,若要替换所有的字符,需要用正则表达式

var stringValue = 'cat,bat,sat,fat';
var result = stringValue.replace('at', 'ond');
console.log(result); // 'cond,bat,sat,fat'
var stringValue = 'cat,bat,sat,fat';
var result = stringValue.replace(/at/g, 'ond');
console.log(result); // 'cond,bond,sond,fond'

replace()默认替换所有的字符串

var stringValue = 'cat,bat,sat,fat';
var result = stringValue.replaceAll('at', 'ond');
console.log(result); // 'cond,bond,sond,fond'

两种方法都不改变源字符串

4、slice()、substring()、substr()

substring()方法返回一个索引和另一个索引之间的字符串

let str = 'hello World,you are a nice gril'
str.substring(2,8) //'llo Wo'
str.substring(8,2) //'llo Wo'

包含start,但是不包含end

如果start=end ,那么返回一个空字符串

如果只有start无end,那么字符串将截取到末尾

如果任一参数小于0或是NaN,它被视为为0。

如果任何一个参数都大于str.length,则被视为是str.length。

如果indexStart大于indexEnd,则返回交换两者的值之后的结果

substr()方法返回从指定位置开始的字符串中指定字符数的字符

str.substr(start, [length])

如果start是正的并且大于或等于字符串的长度,则返回一个空字符串。

若start为负数,则将该值加上字符串长度后再进行计算(如果加上字符串的长度后还是负数,则从0开始截取)。

如果length为0或为负数,返回一个空字符串。如果length省略,则将字符提取到字符串的末尾。

var str = 'abcdefghij';
console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '
console.log(str ); // 'abcdefghij' 不改变源字符串

slice()方法返回一个索引和另一个索引之间的字符串

语法:

str.slice(beginIndex, endIndex)

split():把字符串分割为子字符串数组

var stringValue = 'hello world';
console.log(stringValue.split(' '))  //['hello', 'world']
console.log(stringValue.split(''))   
//['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
console.log(stringValue.split('l')) // ['he', '', 'o wor', 'd']
console.log(stringValue.split('o'))  //['hell', ' w', 'rld']

trim():移除字符串首尾空白,但不能移除中间的空白

var stringValue = ' hello world  ';
console.log(stringValue.trim()); // 'lo world'
console.log(stringValue); // ' hello world  ' 不改变源字符串

indexOf()、lastIndexOf():搜索指定的子字符串,返回子字符串的位置,没有找到则返回-1

indexOf():返回第一个字符的索引

lastIndexOf():返回最后一个字符的索引

var stringValue = 'hello world';
console.log(stringValue.indexOf('o'));  //4
console.log(stringValue.lastIndexOf('o')); //7

toLowerCase():创建原字符串的小写副本

toUpperCase():创建原字符串的大写副本

五、常用数组操作方法

1、join():数组拼接为字符串

var arr = [1,2,3];
console.log(arr.join()); // '1,2,3'
console.log(arr.join('-')); // '1-2-3'
console.log(arr); // [1, 2, 3](原数组不变)

2、push()、pop()

  • push():把里面的内容添加到数组末尾,并返回修改后的长度。
  • pop():移除数组最后一项,返回移除的那个值,减少数组的length。
var arr = ['Lily','lucy','Tom'];
var count = arr.push('Jack','Sean');
console.log(count); // 5
console.log(arr); // ['Lily', 'lucy', 'Tom', 'Jack', 'Sean']
var item = arr.pop();
console.log(item); // Sean
console.log(arr); // ['Lily', 'lucy', 'Tom', 'Jack']

3、shift()、unshift()

  • shift():把数组的第一个元素从其中删除,并返回第一个元素的值
  • unshift():向数组的开头添加一个或更多元素,并返回新的长度
var arr = ['Lily','lucy','Tom'];
var count = arr.unshift('Jack','Sean');
console.log(count); // 5
console.log(arr); //['Jack', 'Sean', 'Lily', 'lucy', 'Tom']
var item = arr.shift();
console.log(item); // Jack
console.log(arr); // ['Sean', 'Lily', 'lucy', 'Tom']

4、sort():将数组里的项从小到大排序

var arr1 = ['a', 'd', 'c', 'b'];
console.log(arr1.sort()); // ['a', 'b', 'c', 'd']

sort()方法比较的是字符串,没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数

arr = [13, 24, 51, 3];
function sortNumber(a,b){
{
   return a - b 
}
console.log(arr.sort(sortNumber))  // [3, 13, 24, 51]
//倒序
function sortNumber1(b,a){
{
   return a - b 
}    
console.log(arr.sort(sortNumber1))  // [3, 13, 24, 51]

5、reverse():反转数组

var arr = [13, 24, 51, 3];
console.log(arr.reverse()); // [3, 51, 24, 13]
console.log(arr); // [3, 51, 24, 13]

6、concat():连接两个或多个数组

var arr = [1,3,5,7];
var arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); // [1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7]

7、slice(start,end):数组截取

var arr = [1,3,5,7,9,11];
var arrCopy = arr.slice(1);
var arrCopy2 = arr.slice(1,4);  //包含1,不包含4
console.log(arrCopy); // [3, 5, 7, 9, 11]
console.log(arrCopy2); // [3, 5, 7] 
console.log(arr); // [1, 3, 5, 7, 9, 11]
//不改变原数组

8、splice(index,howmany):删除、插入和替换

删除

splice(index,howmany)   //第一个是起始位置,第二个参数是删除的个数
let arr = [1,5,6,8,78,95,4,6]
let arrRomve = arr.splice(1,3)
console.log(arr)  //[1,78,95,4,6]

插入

//第一个是起始位置,第二个是删除的个数,第三个是插入的参数
splice(index,del,add)
let arr = [7,9,15,46,97,28]
let arrInject = arr.splice(2,1,5,10)
console.log(arr)  //[7,9,5,10,46,97,28]
console.log(arrInject)  //[15]

替换

splice(index,del,add)  //第一个是起始位置,第二个是删除的个数,第三个是替换的参数
let arr = [7,9,15,46,97,28]
let arrInject = arr.splice(2,1,5)
console.log(arr)  //[7,9,5,46,97,28]
console.log(arrInject)  //[15]