javascript 一维数组与树形数据的转换
let datas = [
{ label: '111', id: 1, parentid: 0 },
{ label: '222', id: 2, parentid: 0 },
{ label: '333', id: 3, parentid: 0 },
{ label: '22221', id: 21, parentid: 2 },
{ label: '22222221', id: 221, parentid: 21 },
{ label: '22222', id: 22, parentid: 2 },
{ label: '11111', id: 11, parentid: 1 },
{ label: '11112', id: 12, parentid: 1 }
]
function arrayToTreeData(data, idkey, pIdKey, children) {
let key = idkey ? idkey : 'id';
let parentKey = pIdKey ? pIdKey : 'parentid';
let childKey = children ? children : 'children';
let r = [];
let tmpMap = [];
for (let i = 0, l = data.length; i < l; i++) {
data[i].key = data[i].id;
data[i].label = data[i].label;
tmpMap[data[i][key]] = data[i];
}
for (let i = 0, l = data.length; i < l; i++) {
if (tmpMap[data[i][parentKey]] && data[i][key] != data[i][parentKey]) {
if (!tmpMap[data[i][parentKey]][childKey]) {
tmpMap[data[i][parentKey]][childKey] = [];
}
tmpMap[data[i][parentKey]][childKey].push(data[i]);
} else {
r.push(data[i]);
}
}
return r;
}
树形转数组
function treeToList(value) {
let nodes = value,
_nodes = [];
_nodes = _nodes.concat(...nodes);
nodes.forEach(n => {
getArray(n, _nodes);
});
return _nodes;
}
function getArray(node, nodes) {
if (node['children'] && node['children'].length) {
nodes.push(...node['children']);
node['children'].forEach(n => getArray(n, nodes));
}
}
console.log(treeToList(datas))
Math
Math.pow(base, exponent) // base基数 exponent指数
//如果 x 是 2 ,且 y 是 7,则 raisePower 函数返回 128 (2 的 7 次幂)。
Math.ceil() //向上取整
Math.floor() //向下取整
Math.abs() //绝对值
alert弹出框中 换行的是 \n
循环切割字符串 ‘网址?’
function test() {
var n = location.search//接受 传过来的
console.log(n) //?inp1=12312&inp2=123333
var arr = n.split('?')[1].split('&')
console.log(arr) // ["inp1=12312", "inp2=123333"]
var obj = {}
for (var i = 0; i < arr.length; i++) {
obj[arr[i].split('=')[0]] = arr[i].split('=')[1]
}
return obj
}
var kk = test()
console.log(kk) //{inp1: "12312", inp2: "123333"}
随机点名器
<style type="text/css">
#ht {
width: 150px;
line-height: 50px;
background: lightskyblue;
border: 1px solid red;
text-align: center;
color: #FFFFFF;
font-size: 20px;
height: 50px;
}
#hb {
width: 150px;
line-height: 50px;
}
</style>
<div id='ht'>
随机点名器
</div>
<div id='hb'>
<button id='but1'>开始</button>
</div>
<script type="text/javascript">
var ht = document.getElementById('ht')
var but1 = document.getElementById('but1')
var but2 = document.getElementById('but2')
var arr = ["1", "2", "3", "4"]
var s
var sum = 0
but1.onclick = function () {
if (sum % 2 == 0) {
clearInterval(s)
but1.innerHTML = '结束'
s = setInterval(go, 10)
} else {
but1.innerHTML = '开始'
clearInterval(s)
}
sum++;
}
// 随机颜色
function go() {
var m = Math.floor(Math.random() * arr.length)
ht.innerHTML = arr[m]
var r = Math.floor(Math.random() * 256)
var g = Math.floor(Math.random() * 256)
var b = Math.floor(Math.random() * 256)
ht.style.background = 'rgb(' + r + "," + g + "," + b + ")"
}
</script>
事件委托,事件代理
<style>
li {
border: 1px solid black;
list-style: none;
}
ul {
background-color: pink;
padding: 20px;
}
</style>
<ul>
<li>iPhone</li>
<li>iPad</li>
<li>Macbook</li>
<li>iPod</li>
</ul>
var parent = document.querySelector('ul')
parent.addEventListener('click', function (e) {
var el = e.target
//console.log(e.target)
while (el.tagName !== 'LI') {
if (el === parent) {
el = null
break
}
el = el.parentNode
console.log(el)
}
if (el) {
console.log(el.innerText)
} else {
console.log('未命中')
}
})
原生轮播图
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
}
#box{width:1000px;height:409px;margin:0 auto;overflow: hidden;
position:relative;
}
#oul li{width:30px;line-height:30px;background: red;float:left;list-style: none;margin-left:10px;text-align: center;border-radius: 50%;}
#oul{position:absolute;bottom:-12px;right:41%;}
#left{position: absolute;left:0px;top:43%}
#right{position: absolute;right:0px;top:43%}
</style>
</head>
<body>
<div id="box">
<img src="img/1.jpg" class="imgx"/>
<img src="img/2.jpg" class="imgx"/>
<img src="img/3.jpg" class="imgx"/>
<img src="img/4.jpg" class="imgx"/>
<img src="img/5.jpg" class="imgx"/>
<img src="img/6.jpg" class="imgx"/>
<ul id="oul">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<img src="img/l.png" id="left"/>
<img src="img/r.png" id="right"/>
</div>
</body>
<script type="text/javascript">
var imgs=document.getElementsByClassName('imgx')//获取图片
var lis=document.getElementById('oul').getElementsByTagName('li')//获取li
var left=document.getElementById('left')//获取左图片
var right=document.getElementById('right')//获取右图片
var m=0;
var s=setInterval(go,800)
function go(x){
for(var i=0;i<lis.length;i++){
imgs[i].style.display="none"
lis[i].style.background=""
}
if(x){
m--;
if(m<0){
m=lis.length-1
}
}else{
m++;
if(m>lis.length-1){
m=0;
}
}
imgs[m].style.display="block"
lis[m].style.background="yellow"
}
for(var i=0;i<lis.length;i++){
lis[i].index=i
lis[i].onmouseover=function(){
clearInterval(s)
for(var j=0;j<lis.length;j++){
lis[j].style.background=""
imgs[j].style.display="none"
}
lis[this.index].style.background='yellowgreen'
imgs[this.index].style.display="block"
}
lis[i].onmouseout=function(){
s=setInterval(go,800)
m=this.index
}
}
left.onmouseover=function(){
clearInterval(s)
}
left.onmouseout=function(){
s=setInterval(go,800)
}
left.onclick=function(){
go(true)
}
right.onmouseover=function(){
clearInterval(s)
}
right.onmouseout=function(){
s=setInterval(go,800)
}
right.onclick=function(){
go()
}
</script>
</html>
时间
setInterval(go,1000)
function go(){
var time1=new Date()//xianzai
var time2=new Date('2020/05/01 00:00:00')//未来
var newTime = time2.getTime()-time1.getTime()//未来的时间减去 现在的时间
var days = parseInt(newTime / (1000 * 60 * 60 * 24));
var hours = parseInt((newTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = parseInt((newTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = (newTime % (1000 * 60)) / 1000;
if(seconds <10){
seconds = '0' + seconds
}
}
// 从后台拿到 事件 转换
time(1577289600000)
time('2019 12 26')
time(time) {
let nowTime = new Date();
let lastTime = new Date(time);
let t = Math.floor((nowTime - lastTime) / 1000);
let Day = Math.floor(t / 86400);
let Hour = Math.floor((t % 86400) / 3600);
let Min = Math.floor(((t % 86400) % 3600) / 60);
let str = "";
if (Day < 1 && Hour < 1) {
str = String(Min);
} else {
let year = lastTime.getFullYear();
let month = lastTime.getMonth() + 1;
let day = lastTime.getDate();
str = year + "年" + getTwo(month) + "月" + day + "日";
}
function getTwo(n) {
return n < 10 ? "0" + n : "" + n;
}
return str;
}
// 将new Date()转换
formatDateForYearAndMonthAndDayunction(date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
var d = date.getDate();
d = d < 10 ? "0" + d : d;
var h = date.getHours();
h = h < 10 ? "0" + h : h;
var minute = date.getMinutes();
minute = minute < 10 ? "0" + minute : minute;
var second = date.getSeconds();
second = second < 10 ? "0" + second : second;
return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
},
将首字母转换为大写
// 将首字母转换为大写
titleCase = str => {
var array = str.toLowerCase().split(" ");
for (var i = 0; i < array.length; i++) {
array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);
//array[i][0] = array[i][0] + 'A' - 'a';
}
var string = array.join(" ");
return string;
}
字符串截取
let str = 'abcdef';
// 0
str = str.slice(0);//返回整个字符串 abcdef
str = str.substring(0);//返回整个字符串 abcdef
str = str.substr(0);//返回整个字符串 abcdef
// 使用一个参数
str = str.slice(2);//截取第二个之后所有的字符 cdef
str = str.substring(2);//截取第二个之后所有的字符 cdef
str = str.substr(2);//截取第二个之后所有的字符 cdef
// 使用两个参数
str = str.slice(2,4);//截取第二个到第四个之间的字符 cd
str = str.substring(2,4);//截取第二个到第四个之间的字符 cd
str = str.substr(2,4);//截取从第3个开始往后数4位之间的字符 cdef
// 使用两个负数
str = str.slice(1,-3);//截取第二个到第四个之间的字符 bc
str = str.substring(1,-3);//截取第二个到第四个之间的字符 a #负数转换为0
str = str.substr(1,-3);//不能为负数,若强行传递负数,会被当成0处理 ' ' #负数转换为0
console.log(str)
JS 正则表达式 获取小括号 中括号 花括号内的内容
var str="123{xxxx}456[我的]789123[你的]456(1389090)789";
var regex1 = /\((.+?)\)/g; // () 小括号
var regex2 = /\[(.+?)\]/g; // [] 中括号
var regex3 = /\{(.+?)\}/g; // {} 花括号,大括号
// 输出是一个数组
console.log(str.match(regex1));
console.log(str.match(regex2));
console.log(str.match(regex3));