js相关知识

1、将数组中的指定元素筛选出来,放入新数组

原数据arr:[ {id:1,name:'123',age:'0'},
                {id:2,name:'234',age:'0'},
                {id:1,name:'456',age:'0'},
                {id:2,name:'789',age:'0'} ]

指定数据newArr:[
                    {id:1,
                       children:[{name:'123',age:'0'},
                                      {name:'456',age:'0'} ]
                      }
                    {id:2,
                       children:[{name:'234',age:'0'},
                      {name:'789',age:'0'} ]
                      }
                 ]

let newArr = [];
this.arr.forEach((item) => {
   let newId = newArr.find((i) => i.id ===item.id);
   if(!newId){
     newArr.push({ id:item.id, children: [ {  name:item.name,age:item.age } ] });
   }else{
    newId.children.push({ name:item.name,age:item.age });
   }
})
console.log(newArr)

2、根据数组统一字段(如id)求两个数组中相同字段的时间差值

let arr = [ {id:'1', time:'11:24:59.132'},{id:'2', time:'11:24:59.132'},]
let arr2 = [ {id:'1',time:'11:25:59.150'}, {id:'2', time:'11:28:33.132'},]
        arr.map((m)=>{
            arr2.map((x)=>{
                if(m.id == x.id){
                    let arrsplit = m.time.split('.')[0].split(":");
                    console.log(arrsplit);
                    let num = Number(arrsplit[0])*3600 + Number(arrsplit[1])*60 + Number(arrsplit[2])
                    console.log(num);
                    let arrsplit2 = x.time.split('.')[0].split(":")
                    let num2 = Number(arrsplit2[0])*3600 + Number(arrsplit2[1])*60 + Number(arrsplit2[2])
                    console.log(num2);
                    let timeDifference = num2 - num;
                    console.log(timeDifference);
                    m['timeDifference'] = timeDifference
                }
            })
        })

3、js遍历循环的几种方法

3.1   for...in 循环

fo…in循环一般用于对象的遍历

var obj = {a: 1, b: 2, c: 3}; 
for (var i in obj) { 
    console.log('键名:', i); 
    console.log('键值:', obj[i]); 
} 
// 键名: a // 键值: 1 // 键名: b // 键值: 2
// 其中 obj为循环的对象, i 为对象中的“键名”。如果对象是数组,那么i就是坐标。

for...in遍历无规律json数组

var json = [
   {dd:'SB',AA:'东东',re1:123}, 
   {cccc:'dd',lk:'1qw'}
]; 
for(var i=0,l=json.length;i<l;i++){
    for(var key in json[i]){
        alert(key+’:'+json[i][key]);
    }
}

for...in遍历有规律的json数组

packJson = [
    {"name": "nikita", "password": "1111"},
    {"name": "tony", "password": "2222"}
];
  
for (var p in packJson) {//遍历json数组时,这么写p为索引,0,1
    alert(packJson[p].name + " " + packJson[p].password);
}

3.2 map循环

map方法将数组的所有成员依次传入参数函数,然后把每一次的执行结果组成一个新数组返回。是返回一个新数组,而不会改变原数组

var numbers = [1, 2, 3];
numbers.map(function (n) { 
     return n + 1; 
}); 
// [2, 3, 4] 
numbers // [1, 2, 3]

map方法接受一个函数作为参数。该函数调用时,map方法向它传入三个参数:当前成员、当前位置和数组本身。

[1, 2, 3].map(function(elem, index, arr) { 
  return elem * index; 
}); 
// [0, 2, 6]

3.3 forEach 循环

forEach方法与map方法很相似,但是,forEach方法不返回值,只用来操作数据。如果数组遍历的目的是为了得到返回值,那么使用map方法,否则使用forEach方法。forEach的用法与map方法一致,参数是一个函数,该函数同样接受三个参数:当前值、当前位置、整个数组。

function log(element, index, array) {
  console.log('[' + index + '] = ' + element); 
} ;
[2, 5, 9].forEach(log); 
// [0] = 2 // [1] = 5 // [2] = 9

3.4 filter过滤循环

filter方法用于过滤数组成员,满足条件的成员组成一个新数组返回。它的参数是一个函数,所有数组成员依次执行该函数,返回结果为true的成员组成一个新数组返回。该方法不会改变原数组。

1, 2, 3, 4, 5].filter(function (elem) {
 return (elem > 3);
}) // [4, 5]

filter方法的参数函数也可以接受三个参数:当前成员,当前位置和整个数组。

[1, 2, 3, 4, 5].filter(function (elem, index, arr) { 
 return index % 2 === 0; 
}); // [1, 3, 5]

此外,filter方法也可以接受第二个参数,用来绑定参数函数内部的this变量。

var obj = { MAX: 3 }; 
var myFilter = function (item) {
 if (item > this.MAX) return true; 
}; 
var arr = [2, 8, 3, 4, 1, 3, 2, 9]; 
arr.filter(myFilter, obj) // [8, 4, 9]

3.5 some(),every()循环遍历,统计数组是否满足某个条件

返回一个布尔值,表示判断数组成员是否符合某种条件

some方法是只要一个成员的返回值是true,则整个some方法的返回值就是true,否则返回false。

var arr = [1, 2, 3, 4, 5];
arr.some(function (elem, index, arr) {
  return elem >= 3;
});// true

every方法则相反,所有成员的返回值都是true,整个every方法才返回true,否则返回false。

var arr = [1, 2, 3, 4, 5];
arr.every(function (elem, index, arr) {
  return elem >= 3;
});// false

some()只要有一个是true,便返回true;而every()只要有一个是false,便返回false.

3.6  reduce(),reduceRight()方法可依次处理数组的每个成员

reduce方法和reduceRight方法依次处理数组的每个成员,最终累计为一个值。它们的差别是,reduce是从左到右处理(从第一个成员到最后一个成员),reduceRight则是从右到左(从最后一个成员到第一个成员),其他完全一样。

[1, 2, 3, 4, 5].reduce(function (a, b) {
  console.log(a, b);
  return a + b;
})
// 1 2
// 3 3
// 6 4
// 10 5
//最后结果:15

3.7 Object,keys遍历对象的属性

Object.keys方法的参数是一个对象,返回一个数组。该数组的成员都是该对象自身的(而不是继承的)所有属性名,且只返回可枚举的属性。

var obj = {
  p1: 123,
  p2: 456
};
Object.keys(obj) // ["p1", "p2"]

4、this指向相关知识

function f1(){
   console.log(this)
}
function f2(){
  'use strict'
   console.log(this)
}
f1()  // window
f2()  // undefined

###########################################################
const foo={
    bar:10,
    fn:function(){
       console.log(this.bar)
       console.log(this)
     }
}

const fn1 = foo.fn
fn1()              // undefined和window,这里this仍然指向window,虽然foo中的fn方法赋值给 
                   // fn1,但是fn1仍然是在window全局环境中执行的

修改

const foo={
    bar:10,
    fn:function(){
       console.log(this.bar) 
       console.log(this)
     }
}

 foo.fn()         // this指向最后调用它的对象

#############call方法改变this指向##############################################

const foo={
    name:'Lucas',
    logName:function(){
        console.log(this.name)   // mike
        console.log(this)        
     }
}

const bar={
    name:'mike'
}
console.log(foo.logName().call(bar))  

##############构造函数和this################################################

function Foo(){
   this.bar = 'Lucas'
}
const instance =new Foo()
console.log(instance.bar)  // Lucas

//创建一个新对象,将构造函数的this指向这个新对象,为新对象添加属性和方法等,最终返回新对象

#############构造函数中出现了显式return的情况############################

#场景1
function Foo(){
    this.user='Lucas'
    const o ={}
    return o
}
const instance =new Foo()
console.log(instance.user)  // undefined

#场景2
function Foo(){
     this.user = 'lucas'
     return 1
}
const instance = new Foo()
console.log(instance.user)  //Lucas

#场景3
function Foo(){
    this.user = 'Lucas'
    const o={user:'admin'}
    return o
}
const instance =new Foo()
console.log(instance.user)  // admin

#总结:如果构造函数中显式返回了一个复杂数据类型(object,array,Date),
那么this就指向这个复杂数据类型,如果返回的是基本数据类型(string,number,
Boolean,undefined,null),那么this仍然指向实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值