javascript常用用法

javascript常用用法

数组相关

//判断数组非空
var  data = [];
if(data.length ==  0 || data == false){
    //data为空数组时,要执行的代码
    alert("data为空");
}

// 浅拷贝
let prefixArray = data.concat();
let prefixArray = data.slice();

// 去除数组第一个元素
array.shift()   

// 去除最后一个元素
array.pop()

// 数组拼接为字符串
array.join('/')

// 数组获取最后一个元素
arr.pop()

// 查找元素在数组的索引 若没有则返回-1
arr.findIndex(item => {
	return item == '查找值'
})

// 过滤数组, 返回满足条件的新数组
arr.filter(item => {
	return item => '判断值'
})

// 删除数组中的某个值
    // 查找指定的元素在数组中的位置
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) {
                return i;
            }
        }
        return -1;
    };

    // 通过索引删除数组元素
    Array.prototype.remove = function(val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    //删除serviceNum数组中对应元素
	let afterData = data.remove(deletedName)

字符串相关

// 将字符串按指定符号分割成数组
string.split()

// 获取最后一个字符
str.charAt(str.length - 1)
str.subStr(str.length-1,1)

// 字符串获取倒数第二个元素
filePath.split('/').slice(-2)[0];

// 将数字字符串转化为数组
let numberArray = numberStringData.split('').map(Number)

// 字符串中是否有某项值
let result = data.indexOf(string) //结果为-1则data中没有string,否则data包含string

对象相关

Object.entries

当data为对象时,value是对象的值,key是对象的索引。
data: {id:‘1’, ip:‘2’} =>>id 1 ip 2
当data为对象数组时,value是数组的其中一个对象,key是数组的位置索引
data:[{ip:1,port:1}, {ip:2, port:2}]=>>0 {ip:1,port:1} 1 {ip:2, port:2}

//data:[{ip:1,port:1}, {ip:2, port:2}]==>>0 {ip:1,port:1} 1 {ip:2, port:2}
//data: {id:'1', ip:'2'} ==>>id 1 ip 2
for (let [key,value] of Object.entries(data)){
    console.log(key);
    console.log(value);
}
//for…of遍历出的结果是value
//for…in遍历出的结果是key

map

// data:[{ip:1,id:1}, {ip:2, id:2}] ==>>0 {ip:1,id:1} 1 {id:2,ip:2}
data.map((value,key)=>{	//value和key的位置不能互换
    console.log(key);
    console.log(value);
})

forEach

//data:[{ip:1,id:1}, {ip:2, id:2}] ==>>0 {ip:1,id:1} 1 {id:2,ip:2}
data.forEach((value,index,array)=>{
    //console.log(array) array为对象数组
    console.log(value)
})

获取对象中某个key的值

Object.keys(data):对于对象返回key值数组,对于数组返回数组下标组成的数组

//data:{ip:'1',id:'2'}
Object.keys(data) //result:['ip','id']

Object.key(array) //result:['0','1'] (处理数组或字符串时返回索引值)
Object.keys(array).map((key)=>{
    console.log(array[key]);  // 获取到属性对应的值,做一些处理
})

js读写excel数据

依赖模块: fs, node-xlsx

遍历文件夹内文件

const fs = require('fs')
fs.readdir(path, function(err, files){
  // files 为文件名数组
  files.forEach(file => {
    // dosomething
  })
})

// 获取当前文件夹内文件名数组
let dir = fs.readdirSync("./")

const data = fs.readFileSync(folderName+'/'+file);

文件写入

// 写入文件
fs.writeFile(`./${Name}.js`, mapping, (err) => {
  if(err){
    console.log(`${Name}.js generate file failed`);
  }
  console.log(`${Name}.js generate file complete`);
})

fs.writeSync(fd,'Hello JavaScript');

读取excel文件

const xlsx = require('node-xlsx');
let sheetList = xlsx.parse(path); // sheetList为数组,存储每个sheet表的数据

获取sheet表数据

let sheet_content = sheetList[i].data; // 获取指定sheet表的数据, i为sheet的顺序位置

获取单元格数据

let code = sheet_content[0][1]; // sheet_content为二维数组 

将二维数组数据写入excel

// 方法一
const xlsx = require('node-xlsx');
let buffer = xlsx.build([
  {
    name:'sheet1',
    data: dataMap // 二维数组
  }        
]);

// 方法二
let XLSX = require('js-xlsx')
/**
     * workboot标准写法
     * {
     *  SheetName:['SheetName'],
     *  Sheets:{
     *      'SheetName':{
     *          '!ref':'A1:E4', //必须要有这个范围才能输出,否则导出的 excel 会是一个空表
     *          A1:{v:'id'},
     *          A2:{v:'name'},
     *      }
     *  }
     * }
     */
let tmpWB = {
  SheetNames: ['mySheet'], //保存的表标题
  Sheets: {
    'mySheet': Object.assign(
      {},
			tmpdata, //内容
      {
        '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
      }
    )
  }
};
//导出excel
XLSX.writeFile(tmpWB, 'output.xlsx');

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是几个常用内置对象的使用例题: 1. 字符串对象 ```js let str = "hello world"; // 获取字符串长度 console.log(str.length); // 11 // 转换为大写字母 console.log(str.toUpperCase()); // "HELLO WORLD" // 替换字符串 console.log(str.replace("world", "JavaScript")); // "hello JavaScript" ``` 2. 数组对象 ```js let arr = [1, 2, 3, 4, 5]; // 获取数组长度 console.log(arr.length); // 5 // 获取数组中第一个元素 console.log(arr[0]); // 1 // 循环遍历数组 for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // 在数组末尾添加一个元素 arr.push(6); console.log(arr); // [1, 2, 3, 4, 5, 6] // 删除数组中最后一个元素 arr.pop(); console.log(arr); // [1, 2, 3, 4, 5] ``` 3. Date对象 ```js let now = new Date(); // 获取当前时间 console.log(now); // Sat Jul 10 2021 14:32:06 GMT+0800 (中国标准时间) // 获取当前时间的年份 console.log(now.getFullYear()); // 2021 // 获取当前时间的月份(0表示1月) console.log(now.getMonth()); // 6 // 获取当前时间的日期 console.log(now.getDate()); // 10 ``` 4. Math对象 ```js // 获取随机数(0-1之间) console.log(Math.random()); // 0.123456789 // 获取一个数的绝对值 console.log(Math.abs(-10)); // 10 // 获取两个数的最大值 console.log(Math.max(1, 2, 3, 4, 5)); // 5 ``` 以上只是一些常用内置对象的例题,JavaScript内置对象非常多,不同的对象有不同的属性和方法,需要根据实际需求灵活运用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值