js中Array的用法和console调试

直接步入正题!

一、console

1.更多的输出方法

可参考C语言中的输出格式。

%s 字符串
%d 整数
%f 浮点数
%o object
%c 设定输出的样式,在之后的文字将按照第二个参数里的值进行显示。

例如:

console.log("It's string %s","log"); //It's string log
console.log("%c3D Text"," text-shadow: 0 1px 0 #ccc,0 2px 0 #c9c9c9,0 3px 0 #bbb,0 4px 0 #b9b9b9,0 5px 0 #aaa,0 6px 1px rgba(0,0,0,.1),0 0 5px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.3),0 3px 5px rgba(0,0,0,.2),0 5px 10px rgba(0,0,0,.25),0 10px 10px rgba(0,0,0,.2),0 20px 20px rgba(0,0,0,.15);font-size:5em");

2.清空控制台

快捷键:control + L
控制台命令:console.clear()

3.不同样式的输出

console.warn()
console.error()
console.info(“用于输出提示信息”)
console.debug(“用于输出调试信息”)

4.打印DOM节点

const p = document.querySelector(‘p’);
console.log(p);
console.dir(p);
.log :输出这个DOM的HTML标签
.dir :输出这个DOM元素的属性列表

5.打印表格

console.table();   
console.table(名称,元素key);
例如:
    console.table(dogs,["name"]); //打印dogs表格中的name标签。

6.分组打印( group( ) )

const dogs = [{ name: 'Snickers', age: 2 }, { name: 'hugo', age: 8 }];
dogs.forEach(dog => {
    console.group(`${dog.name}`);        
//  console.groupCollapsed(`${dog.name}`);  // 列表默认叠起状态
    console.log(`${dog.name}`);
    console.log(`${dog.age}`);
    console.log(`${dog.name} 有 ${dog.age} 岁了`);
    console.groupEnd();
});

7.计数打印

cosole.count() 可以对书粗的对象进行计数。但需要注意的是这里的计数对象仅限于由count()输出的内容,并非所有console中输出。

8.time 计时

用time(“name”)和timeEnd(“name”)分别控制开始点和结束点,它们两的参数表示当前计时的名称,可以定义但需要保持相同,所以如果想看异步获取数据花了多场事件,可以这样写:

console.time('fetch my data');
fetch("https://api.github.com/users/soyaine")
  .then(data => data.json())
  .then(data => {
  console.timeEnd('fetch my data');
  console.log(data);
});

9.断点调试

直接在控制台打断点进行调试。

二、Array

1、数组的创建

var arrayObj = new Array(); //创建一个数组
var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限,是长度
var arrayObj = new Array(element0, element1, ..., elementn); //创建一个数组并赋值

2、数组元素的访问

var testGetArrValue=arrayObj[1]; //获取数组的元素值
arrayObj[1]= "这是新值"; //给数组元素赋予新的值

3、数组元素的添加

arrayObj. push( );// 将一个或多个新元素添加到数组结尾,并返回数组新长度
arrayObj.unshift( );// 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度
arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]);//将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回""。

4、部分数组对象属性详解

下面给出数据源,下面的操作都以以下数据源为准。

const inventors = [{
            first:'Albert',
            last: 'Einstein',
            year: 1879,
            passed:1955        
        },
        {
        first: 'Isaac',
        last: 'Newton',
        year: 1643,
        passed: 1727
      },
      {
        first: 'Galileo',
        last: 'Galilei',
        year: 1564,
        passed: 1642
      },
      {
        first: 'Marie',
        last: 'Curie',
        year: 1867,
        passed: 1934
      },
      {
        first: 'Johannes',
        last: 'Kepler',
        year: 1571,
        passed: 1630
      },
      {
        first: 'Nicolaus',
        last: 'Copernicus',
        year: 1473,
        passed: 1543
      },
      {
        first: 'Max',
        last: 'Planck',
        year: 1858,
        passed: 1947
      },
      {
        first: 'Katherine',
        last: 'Blodgett',
        year: 1898,
        passed: 1979
      },
      {
        first: 'Ada',
        last: 'Lovelace',
        year: 1815,
        passed: 1852
      },
      {
        first: 'Sarah E.',
        last: 'Goode',
        year: 1855,
        passed: 1905
      },
      {
        first: 'Lise',
        last: 'Meitner',
        year: 1878,
        passed: 1968
      },
      {
        first: 'Hanna',
        last: 'Hammarström',
        year: 1829,
        passed: 1909
      }      
    ];
const people = [
            { name: 'Wes', year: 1988 },
            { name: 'Kait', year: 1986 },
            { name: 'Irv', year: 1970 },
            { name: 'Lux', year: 2015 }
        ];
const comments = [
            { text: 'Love this!', id: 523423 },
            { text: 'Super good', id: 823423 },
            { text: 'You are the best', id: 2039842 },
            { text: 'Ramen is my fav food ever', id: 123523 },
            { text: 'Nice Nice Nice!', id: 542328 },
            { text: 'Super', id: 823423 }
        ];

1.filter( )

过滤操作,筛选运行结果是true的组成数组返回。

//筛选16世纪出生的发明家
const fifteen =inventors.filter(inventor =>(inventor.year >= 1500 && inventor.year < 1600));
console.table(fifteen);

2.map( )

把数组中的每个元素进行处理后,返回一个新的数组。

//展示他们的姓和名
const fullNames = inventors.map(inventor=> `${inventor.first} ${inventor.last}`);
console.log(fullNames);

3.sort

默认情况下,将数组以字符串的形式进行升序排列,但sort也可以接受一个函数作为参数。所以需要对数字大小排序时需要自己设定一个比较函数。

const ordered =inventors.sort((a,b) => a.year > b.year ? 1: -1);
console.table(ordered);

4.reduce

可以给指定的条件下统计物品的数量。
是一个归并数组的方法,它接受一个函数作为参数(这个函数可以理解成累加器),它会遍历数组的所有项,然后构建一个最终的返回值,这个值是这个累加器的第一个参数。第二个参数的0是遍历的初始值。

//计算所有的发明家加起来一共活了多少岁
const totalYears =inventors.reduce((total,inventor) =>{
        return total+(inventor.passed -inventor.year);
    },0);
console.log(totalYears);

5.some( )

判断数组中某一个元素是满足这个条件.
some() 方法会依次执行数组的每个元素:如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。如果没有满足条件的元素,则返回false。

//1. 是否至少有一人年满19周岁?
const isAdult = people.some(person=>(new Date().getFullYear()-person.year )>= 19); 
console.log(isAdult);
//true

注意: some() 不会对空数组进行检测。 some() 不会改变原始数组。

6.every()

判断数组所有元素是否满足这个条件
返回值:true或者flase
true:代表数组中所有数据都满足条件
flase:至少有一条不满足条件

//是否每一个人都年满19周岁
const isEvery = people.every(person=>(new Date().getFullYear()-person.year )>= 19);
console.log(isEvery);
//false

7.find()&findindex()

find(),查找某一个元素是否存在。如果有满足条件对象,返回该对象,否则返回undefined。
findindex(),查找指定一个元素的索引号;满足条件的当前对象在数组中的索引,如果找不到满足条件对象,返回-1。

//find
const findComment = comments.find(comment=>(comment.id === 823423));
console.log(findComment);

//findindex
const find_Index = comments.findIndex(index=>(index.id===823423));
console.log(find_Index);

注:如果一个数组中有多个相同的元素,查找到的第一个后返回,后面的不做处理。

8.splice( )与slice( )

splice( ) 通过删除现有元素或添加新元素来更改一个数组的内容。会修改原数组
slice( ) 返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象。原始数组不会被修改

/*
Array.prototype.splice()
array.splice(start);   从索引start开始移除后面所有的元素
array.splice(start,deleteCount); 从索引start元素删除deleteCount个元素。
array.splice(start,deleteCount,item1,item2,item3,……);  从索引start元素删除deleteCount个元素,并插入item1,……

slice: splice会修改原数组,slice不会改变原数组的值。
arr.slice()  === arr.slice(0,arr.length-1)
arr.slice(begin) === arr.slice(begin,arr.length-1)
arr.slice(begin, end):创建一个新数组,将索引begin-end(不包含end)的元素放到新数组中并返回新数组,原数组不被修改*/
const findComentsIndex = comments.findIndex(index=>(index.id===823423));
// comments.splice(findComentsIndex.index,1);
const newComents = [
    ...comments.slice(0,find_Index),
    ...comments.slice(find_Index+1)
    ];
console.log(newComents);
// console.log(comments);

5、数组对象的属性

1.length属性

设置或返回数组中元素的数目。

2.prototype属性

使您有能力向对象添加属性和方法。

function array_max()
 {
    var i,
    max = this[0];
    for (i = 1; i < this.length; i++)
    {
        if (max < this[i])
        max = this[i];
    }
    return max;
}
Array.prototype.max = array_max;
var x = new Array(9, 2, 9, 10, 5, 99);
var y = x.max();
//99

3.constructor属性

返回对创建此对象的数组函数的引用

constructor 属性是所有具有 prototype 的对象的成员。它们包括除 Global 和 Math 对象以外的所有 JScript 固有对象。constructor 属性保存了对构造特定对象实例的函数的引用。

例如:

function MyFunc {
   // 函数体。
}
6
y = new MyFunc;
if (y.constructor == MyFunc) // 进行处理(条件为真)。

对于数组来说:y = new Array();
posted @ 2017-08-04 18:00  qinqinglyq  阅读(811)  评论(0)    收藏  举报