Comments (3)
13、找出字符串中出现最多的字母
function getMaxNumberOfChar(str) {
return (str + '').split('').reduce(function (pre, cur, index, arr) {
cur in pre ? pre[cur]++ : (pre[cur] = 1);
pre[cur] > pre.value && (pre.char = cur, pre.value = pre[cur]);
return pre;
}, { value: 0 });
}
getMaxNumberOfChar('ababccdeajxac') // Object {value: 4, a: 4, char: "a", b: 2, c: 3…}
//此外,可以考虑用正则
function getMaxNumberOfChar(str) {
return (str + '').split('').sort().join('').match(/(\w)\1*/g).reduce(function (pre, cur) {
return cur.length > pre.value ? { value: cur.length, char: cur[0] } : pre;
}, { value: 0 })
}
getMaxNumberOfChar('ababccdeajxac') // Object {value: 4, char: "a"}
14、一键复制
需要复制的元素为非input、textera
if ($.isIOS()) {
var range = document.createRange();
range.selectNode(document.getElementById('weixin'));
var selection = window.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
} else {
var clipboard = new ClipboardJS('#copyBtn');
clipboard.on('success', function (e) {
$.alert('复制成功');
});
clipboard.on('error', function (e) {
console.log(e);
});
}
15、对象数组的去重
var arr = [{
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}, {
"name": "ZYTA",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "BBBBBB.doc"
}, {
"name": "ZDTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "CCCCCC.doc"
}, {
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}];
var hash = {};
arr = arr.reduce(function(item, next) {
hash[next.name] ? '' : hash[next.name] = true && item.push(next);
return item
}, [])
console.log(arr);
作者:Roy-skywalker
链接:https://juejin.im/post/5b17a2c251882513e9059231
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
16、复杂判断逻辑优雅写法
if...else写法
const onButtonClick = (status)=>{
if(status == 1){
sendLog('processing')
jumpTo('IndexPage')
}else if(status == 2){
sendLog('fail')
jumpTo('FailPage')
}else if(status == 3){
sendLog('fail')
jumpTo('FailPage')
}else if(status == 4){
sendLog('success')
jumpTo('SuccessPage')
}else if(status == 5){
sendLog('cancel')
jumpTo('CancelPage')
}else {
sendLog('other')
jumpTo('Index')
}
}
作者:Think.
链接:https://juejin.im/post/5bdfef86e51d453bf8051bf8
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
switch写法
const onButtonClick = (status)=>{
switch (status){
case 1:
sendLog('processing')
jumpTo('IndexPage')
break
case 2:
case 3:
sendLog('fail')
jumpTo('FailPage')
break
case 4:
sendLog('success')
jumpTo('SuccessPage')
break
case 5:
sendLog('cancel')
jumpTo('CancelPage')
break
default:
sendLog('other')
jumpTo('Index')
break
}
}
// case 2和case 3逻辑一样的时候,可以省去执行语句和break,则case 2的情况自动执行case 3的逻辑。
作者:Think.
链接:https://juejin.im/post/5bdfef86e51d453bf8051bf8
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
优雅写法
const actions = {
'1': ['processing','IndexPage'],
'2': ['fail','FailPage'],
'3': ['fail','FailPage'],
'4': ['success','SuccessPage'],
'5': ['cancel','CancelPage'],
'default': ['other','Index'],
}
const onButtonClick = (status)=>{
let action = actions[status] || actions['default'],
logName = action[0],
pageName = action[1]
sendLog(logName)
jumpTo(pageName)
}
作者:Think.
链接:https://juejin.im/post/5bdfef86e51d453bf8051bf8
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
将判断条件作为对象的属性名,将处理逻辑作为对象的属性值,适合一元条件判断
new Map写法
const actions = new Map([
['guest_1', ()=>{/*do sth*/}],
['guest_2', ()=>{/*do sth*/}],
['guest_3', ()=>{/*do sth*/}],
['guest_4', ()=>{/*do sth*/}],
['guest_5', ()=>{/*do sth*/}],
['master_1', ()=>{/*do sth*/}],
['master_2', ()=>{/*do sth*/}],
['master_3', ()=>{/*do sth*/}],
['master_4', ()=>{/*do sth*/}],
['master_5', ()=>{/*do sth*/}],
['default', ()=>{/*do sth*/}],
])
/**
* 按钮点击事件
* @param {string} identity 身份标识:guest客态 master主态
* @param {number} status 活动状态:1 开团进行中 2 开团失败 3 开团成功 4 商品售罄 5 有库存未开团
*/
const onButtonClick = (identity,status)=>{
let action = actions.get(`${identity}_${status}`) || actions.get('default')
action.call(this)
}
作者:Think.
链接:https://juejin.im/post/5bdfef86e51d453bf8051bf8
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
把两个条件拼接成字符串,并通过以条件拼接字符串作为键,以处理函数作为值的Map对象进行查找并执行,这种写法在多元条件判断时候尤其好用。
当然上述代码如果用Object对象来实现也是类似的:
const actions = {
'guest_1':()=>{/*do sth*/},
'guest_2':()=>{/*do sth*/},
//....
}
const onButtonClick = (identity,status)=>{
let action = actions[`${identity}_${status}`] || actions['default']
action.call(this)
}
作者:Think.
链接:https://juejin.im/post/5bdfef86e51d453bf8051bf8
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
from blogs.
17、 n个数组,找出相同的项
function intersect() {
let sets = [];
for (let i = 0; i < arguments.length; i++) {
const arg = arguments[i];
let set = new Set(arg);
sets.push(set);
}
let result;
for (let i = 0; i < sets.length - 1; i++) {
if (i == 0) {
result = [...sets[i]].filter(item => sets[i + 1].has(item));
} else {
result = [...result].filter(item => sets[i + 1].has(item));
}
}
return result;
}
注意: 数组为obj结构时,要是同一个指针(同一个对象的引用)才会返回 true,否则,new Set().has(item)返回 false
18、判断是否为页面底部
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
19、slice、splice
20、两个对象数组去重
arr1= [
{
id: 1,
name: 1
},
{
id: 2,
name: 2
}
]
arr2 = [
{
id: 1,
name: 1
},
{
id: 2,
name: 2
},
{
id: 3,
name: 3
}
]
temp = []
arr2.forEach(item => {
if(arr1.every(i => item.id != i.id))){
temp.push(item)
}
})
from blogs.
循环中的sleep
需求:循环中隔一段时间执行循环体的代码
- 原生 for 循环
const sleep = () => new Promise((res, rej) => setTimeout(res, 5000));
(async () => {
for (let i = 0; i < 9; i++) {
console.log(i);
await sleep();
}
})();
- forEach
const asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
};
asyncForEach(arr, async item => {
await sleep();
console.log(item)
})
from blogs.
Related Issues (11)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blogs.