JavaScript 工具方法

1. 转换String类型

// 1、 toString()
const num = 1;
const newString = num.toString();

console.log(newString);

const a = true;
const b = a.toString();
console.log(b);

// toString 中的参数代表进制
console.log(num.toString(10))

// 2、String()
var num1 = 1;
var num2 = String(num1);
console.log(num2);

// 3、拼接 一个空的字符 ""
console.log(num1 + "");

2. 数组转换逗号字符串

const newlist = this.multipleSelection1
let index = 0
let newString = ''
for (let i = 0; i < newlist.length; i++) {
  index++
  if (index < newlist.length) {
      newString = newString + newlist[i].PROJECT_ID + ','
  } else {
      newString = newString + newlist[i].PROJECT_ID
      }
  }
console.log(newString)

 3.日期月份小于10月前面加0

export function newdateformat(date) {
  const newDate = new Date(date)
  const year = parseInt(newDate.getFullYear())
  const month = newDate.getMonth() + 1
  return year + '' + month.toString().padStart(2, '0')
}

4.删除点击事件传的参数在数组删除

const todolist = []
remstu(data) {
  todolist = todolist.filter((x) => x !== data)
}

5. 在数组中添加对象

const list = []

const obj = {
    name: '',
    age: ''
}

aadobj() {
    const newobj = Object.assign({}, obj);
    newobj.name = ''
    newobj.age = ''
    list.push(newobj)
}

 6.金额千元符【区分币种】

// 转千位符方法
export function toThousands(num = 0, currency = 'normal', point = 2) {
  let zero = '.00'
  if (num === null) num = 0
  if (currency === 'JPY') zero = ''
  var [sInt, sFloat] = (Number.isInteger(num) ? `${num}` : num.toFixed(point)).split('.')
  sInt = sInt.replace(/\d(?=(\d{3})+$)/g, '$&,')
  return sFloat ? `${sInt}.${sFloat}` : `${sInt}` + `${zero}`
}

 7.获取字符串最后一位指定字符后面字符

const index = file.name.lastIndexOf('.')
const newString = file.name.substring(index + 1, file.name.length)
console.log(newString)

8. 数组对象按照从小到大排序【冒泡排序】

const tablelist = [
 {
    num:3
  },
  {
    num:4
  },
  {
    num:1
  }   
]

for (var i = 1; i < tablelist.length; i++) {
  // 内层循环:控制每轮比较次数  数组长度-i
  for (var j = 0; j < tablelist.length - i; j++) {
    // 如果当前的元素(j)大于下一个元素(j+1),则交换位置
    if (tablelist[j].num >tablelist[j + 1].num) {
      var t = tablelist[j]
      tablelist[j] = tablelist[j + 1]
      tablelist[j + 1] = t
    }
  }
}

9. 获取数组最大数最小数

// 最大值
Math.max.apply(null, List)
// 最小值
Math.min.apply(null, List)

 

posted @ 2020-06-09 16:36  皮一皮很开心  阅读(175)  评论(0编辑  收藏  举报