JS常用方法&技巧

Number数字

1.字符串转换为数字的方法:

parseInt/Number

String字符串

1.replace()

  • 理解

replace方法可以将视图中获取的内容替换成最终数据

stringObject.replace(regexp/substr,replacement)

//我的理解
data.replace("html替换源",js要替换的数据变量名)
  • 例子

app.js

//需要响应数据,假设响应数据值为data
var msg="<h1> test</h1>"
data.replace("xox",msg);

index.html

<div>xox</div>

2.字符串大小写转换

(1).转换为大写toLocaleUpperCase()

(2).转换为小写toLocaleLowerCase()

3.字符串去除空格

str.trim()方法

var str="sfds sdf sdf"
console.log(str.trim())

Array数组

1.forEach()

  • 定义

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。

  • 用法
array.forEach(function(currentValue, index, arr), thisValue)
//array:要遍历的数组名
//currentValue:数组值名称
//index:可选。数组索引
//arr:	可选。当前元素所属的数组对象。
//thisValue:可选。传递给函数的值一般用 "this" 值。
  • 例子
var msgs = [{
        name: '张三',
        content: '你好我是张三',
        create_time: '2001-12-23'
    },
    {
        name: '李四',
        content: '你好我是李四',
        create_time: '2001-12-23'
    }
]
 // 创建动态页面
                var msghtml = ""
                msgs.forEach(function (item) {
                    msghtml += `<tr><td>${item.name}</td><td>${item.content}</td><td>${item.create_time}</td></tr>`
                })
                var data=data.replace("{content}",msghtml);//{content}html中获取

2.push()

数组中添加新元素

3.pop()

数组中移出最后一个元素

Boolean布尔

Date日期

使用前:var d=new Date

1.d.toLocaleDateString()

返回2021/11/28格式日期

2.当前时间戳

Date.now()

Global全局

Math数学

RegExp正则

posted @ 2021-11-28 00:05  禾耳  阅读(67)  评论(0)    收藏  举报