数组
删除一个
js
function removeitem(arr, item) {
let newstr = str.replace(new RegExp(item, `g`), ``)
console.log(arr)
return [...newstr]
}
console.log(removeitem([1, 2, 3, 4, 2], 2))
function removeitem(arr, item) {
let newstr = str.replace(new RegExp(item, `g`), ``)
console.log(arr)
return [...newstr]
}
console.log(removeitem([1, 2, 3, 4, 2], 2))
ts
// 0.0.2/arrayUniqueFilter.js
const arr = [1, 2, 11, 22, 11, 1, 11, 22, 1, 2]
const unique = (arr) =>
arr.filter(
(element, index, self) =>
// Self.indexOf(element) 每次都从数组第一个元素开始往下查
self.indexOf(element) === index,
)
console.log(unique(arr)) // [1, 2, 11, 22]
// 上面可简写为
const unique2 = (arr) =>
arr.filter((element, index, self) => self.indexOf(element) === index)
console.log(unique2(arr)) // [1, 2, 11, 22]
// 元素非对象
const arr3 = [
{ id: 1, name: `张三` },
{ id: 2, name: `李四` },
{ id: 11, name: `王五` },
{ id: 1, name: `张三` },
{ id: 11, name: `王五` },
{ id: 3, name: `李四` },
]
const unique3 = (arr, id) => {
const cache = []
for (const item of arr) {
if (cache.find((v) => v[id] === item[id])) {
continue
}
cache.push(item)
}
return cache
}
console.log(unique3(arr3, `id`)) // [{id: 1, name: "张三"}, {id: 2, name: "李四"}, {id: 11, name: "王五"}, {id: 3, name: "李四"}]
export {}
// 0.0.2/arrayUniqueFilter.js
const arr = [1, 2, 11, 22, 11, 1, 11, 22, 1, 2]
const unique = (arr) =>
arr.filter(
(element, index, self) =>
// Self.indexOf(element) 每次都从数组第一个元素开始往下查
self.indexOf(element) === index,
)
console.log(unique(arr)) // [1, 2, 11, 22]
// 上面可简写为
const unique2 = (arr) =>
arr.filter((element, index, self) => self.indexOf(element) === index)
console.log(unique2(arr)) // [1, 2, 11, 22]
// 元素非对象
const arr3 = [
{ id: 1, name: `张三` },
{ id: 2, name: `李四` },
{ id: 11, name: `王五` },
{ id: 1, name: `张三` },
{ id: 11, name: `王五` },
{ id: 3, name: `李四` },
]
const unique3 = (arr, id) => {
const cache = []
for (const item of arr) {
if (cache.find((v) => v[id] === item[id])) {
continue
}
cache.push(item)
}
return cache
}
console.log(unique3(arr3, `id`)) // [{id: 1, name: "张三"}, {id: 2, name: "李四"}, {id: 11, name: "王五"}, {id: 3, name: "李四"}]
export {}
ts
// 0.0.2/array_algorithms.js
const arr1 = [1, 7, 4, 5, 2, 1, 5, 3, 6, 2, 1, 3]
const arr2 = [2, 4, 3, 4, 5, 5, 5]
const intersection = (arr1, arr2) => {
const map = new Map()
const arr = []
// 键值对,键是 value,值是 value 出现次数, 出现次数累加
for (let i = 0; i < arr1.length; i++) {
const value = arr1[i]
console.log(map)
console.log(value)
let valueInMap = map.get(value)
console.log(valueInMap)
valueInMap = (valueInMap ? valueInMap : 0) + 1
console.log(valueInMap)
map.set(value, valueInMap)
console.log(map)
}
// 键值对,中转 map 判断第二个数组的值是否存在,存在就留下来,然后 map 值次数减1
for (let i = 0; i < arr2.length; i++) {
const value = arr2[i]
if (map.has(value) && map.get(value) !== 0) {
arr.push(value)
map.set(value, map.get(value) - 1)
}
}
return arr
}
console.log(intersection(arr1, arr2)) // [ 2, 4, 3, 5, 5 ]
// 0.0.2/array_algorithms.js
const arr1 = [1, 7, 4, 5, 2, 1, 5, 3, 6, 2, 1, 3]
const arr2 = [2, 4, 3, 4, 5, 5, 5]
const intersection = (arr1, arr2) => {
const map = new Map()
const arr = []
// 键值对,键是 value,值是 value 出现次数, 出现次数累加
for (let i = 0; i < arr1.length; i++) {
const value = arr1[i]
console.log(map)
console.log(value)
let valueInMap = map.get(value)
console.log(valueInMap)
valueInMap = (valueInMap ? valueInMap : 0) + 1
console.log(valueInMap)
map.set(value, valueInMap)
console.log(map)
}
// 键值对,中转 map 判断第二个数组的值是否存在,存在就留下来,然后 map 值次数减1
for (let i = 0; i < arr2.length; i++) {
const value = arr2[i]
if (map.has(value) && map.get(value) !== 0) {
arr.push(value)
map.set(value, map.get(value) - 1)
}
}
return arr
}
console.log(intersection(arr1, arr2)) // [ 2, 4, 3, 5, 5 ]
ts
let str = 'abcabcabcbbccccc'
let num = 0
let char = ''
let arr = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
// 使其按照一定的次序排列
let compress = function (chars) {
chars = chars.join('')
let temp = []
let re = /(\w)\1+/g
chars.replace(re, ($0, $1) => {
temp.push($1)
temp.push(String($0.length))
return temp
})
console.log(chars)
return chars.length
}
console.log(compress(arr))
export {}
let str = 'abcabcabcbbccccc'
let num = 0
let char = ''
let arr = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
// 使其按照一定的次序排列
let compress = function (chars) {
chars = chars.join('')
let temp = []
let re = /(\w)\1+/g
chars.replace(re, ($0, $1) => {
temp.push($1)
temp.push(String($0.length))
return temp
})
console.log(chars)
return chars.length
}
console.log(compress(arr))
export {}
ts
function f2c(x) {
function convert(str, p1, offset, s) {
return ((p1 - 32) * 5) / 9 + 'C'
}
let s = String(x)
let test = /(\d+(?:\.\d*)?)F\b/g
return s.replace(test, convert)
}
console.log(f2c('232F'))
function f2c(x) {
function convert(str, p1, offset, s) {
return ((p1 - 32) * 5) / 9 + 'C'
}
let s = String(x)
let test = /(\d+(?:\.\d*)?)F\b/g
return s.replace(test, convert)
}
console.log(f2c('232F'))
ts
const num = 123456654321
const str = 'ABababababab'
const handle = (params) => {
let str_1 = String(params)
.replace(/[^0-9A-Za-z]/g, '')
.toLowerCase()
let str_2 = str_1.split('').reverse().join()
return str_1 === str_2 ? true : false
}
handle(num) // true
handle(str) // false
export {}
const num = 123456654321
const str = 'ABababababab'
const handle = (params) => {
let str_1 = String(params)
.replace(/[^0-9A-Za-z]/g, '')
.toLowerCase()
let str_2 = str_1.split('').reverse().join()
return str_1 === str_2 ? true : false
}
handle(num) // true
handle(str) // false
export {}
ts
// 三种状态
const PENDING = "pending";
const RESOLVED = "resolved";
const REJECTED = "rejected";
// promise 接收一个函数参数,该函数会立即执行
function MyPromise(fn) {
let _this = this;
_this.currentState = PENDING;
_this.value = undefined;
// 用于保存 then 中的回调,只有当 promise
// 状态为 pending 时才会缓存,并且每个实例至多缓存一个
_this.resolvedCallbacks = [];
_this.rejectedCallbacks = [];
_this.resolve = function (value) {
if (value instanceof MyPromise) {
// 如果 value 是个 Mypromise,递归执行
return value.then(_this.resolve, _this.reject)
}
setTimeout(() => { // 异步执行,保证执行顺序
if (_this.currentState === PENDING) {
_this.currentState = RESOLVED;
_this.value = value;
_this.resolvedCallbacks.forEach(cb => cb());
}
})
};
_this.reject = function (reason) {
setTimeout(() => { // 异步执行,保证执行顺序
if (_this.currentState === PENDING) {
_this.currentState = REJECTED;
_this.value = reason;
_this.rejectedCallbacks.forEach(cb => cb());
}
})
}
// 用于解决以下问题
// new Mypromise(() => throw Error('error))
try {
fn(_this.resolve, _this.reject);
} catch (e) {
_this.reject(e);
}
}
MyPromise.prototype.then = function (onResolved, onRejected) {
let self = this;
// 规范 2.2.7,then 必须返回一个新的 promise
let promise2;
// 规范 2.2.onResolved 和 onRejected 都为可选参数
// 如果类型不是函数需要忽略,同时也实现了透传
// Mypromise.resolve(4).then().then((value) => console.log(value))
onResolved = typeof onResolved === 'function' ? onResolved : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => throw r;
if (self.currentState === RESOLVED) {
return (promise2 = new MyPromise(function (resolve, reject) {
// 规范 2.2.4,保证 onFulfilled,onRjected 异步执行
// 所以用了 setTimeout 包裹下
setTimeout(function () {
try {
let x = onResolved(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (reason) {
reject(reason);
}
});
}));
}
if (self.currentState === REJECTED) {
return (promise2 = new MyPromise(function (resolve, reject) {
setTimeout(function () {
// 异步执行onRejected
try {
let x = onRejected(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (reason) {
reject(reason);
}
});
}));
}
if (self.currentState === PENDING) {
return (promise2 = new MyPromise(function (resolve, reject) {
self.resolvedCallbacks.push(function () {
// 考虑到可能会有报错,所以使用 try/catch 包裹
try {
let x = onResolved(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (r) {
reject(r);
}
});
self.rejectedCallbacks.push(function () {
try {
let x = onRejected(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (r) {
reject(r);
}
});
}));
}
};
// 规范 2.3
function resolutionProcedure(promise2, x, resolve, reject) {
// 规范 2.3.1,x 不能和 promise2 相同,避免循环引用
if (promise2 === x) {
return reject(new TypeError("Error"));
}
// 规范 2.3.2
// 如果 x 为 Mypromise,状态为 pending 需要继续等待否则执行
if (x instanceof MyPromise) {
if (x.currentState === PENDING) {
x.then(function (value) {
// 再次调用该函数是为了确认 x resolve 的
// 参数是什么类型,如果是基本类型就再次 resolve
// 把值传给下个 then
resolutionProcedure(promise2, value, resolve, reject);
}, reject);
} else {
x.then(resolve, reject);
}
return;
}
// 规范 2.3.3.3.3
// reject 或者 resolve 其中一个执行过得话,忽略其他的
let called = false;
// 规范 2.3.3,判断 x 是否为对象或者函数
if (x !== null && (typeof x === "object" || typeof x === "function")) {
// 规范 2.3.3.2,如果不能取出 then,就 reject
try {
// 规范 2.3.3.1
let then = x.then;
// 如果 then 是函数,调用 x.then
if (typeof then === "function") {
// 规范 2.3.3.3
then.call(
x,
y => {
if (called) return;
called = true;
// 规范 2.3.3.3.1
resolutionProcedure(promise2, y, resolve, reject);
},
e => {
if (called) return;
called = true;
reject(e);
}
);
} else {
// 规范 2.3.3.4
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else {
// 规范 2.3.4,x 为基本类型
resolve(x);
}
}
let p=new MyPromise(() => {
console.log('thisis demo')
})
p.then(() => {
console.log('lllee')
})
// 三种状态
const PENDING = "pending";
const RESOLVED = "resolved";
const REJECTED = "rejected";
// promise 接收一个函数参数,该函数会立即执行
function MyPromise(fn) {
let _this = this;
_this.currentState = PENDING;
_this.value = undefined;
// 用于保存 then 中的回调,只有当 promise
// 状态为 pending 时才会缓存,并且每个实例至多缓存一个
_this.resolvedCallbacks = [];
_this.rejectedCallbacks = [];
_this.resolve = function (value) {
if (value instanceof MyPromise) {
// 如果 value 是个 Mypromise,递归执行
return value.then(_this.resolve, _this.reject)
}
setTimeout(() => { // 异步执行,保证执行顺序
if (_this.currentState === PENDING) {
_this.currentState = RESOLVED;
_this.value = value;
_this.resolvedCallbacks.forEach(cb => cb());
}
})
};
_this.reject = function (reason) {
setTimeout(() => { // 异步执行,保证执行顺序
if (_this.currentState === PENDING) {
_this.currentState = REJECTED;
_this.value = reason;
_this.rejectedCallbacks.forEach(cb => cb());
}
})
}
// 用于解决以下问题
// new Mypromise(() => throw Error('error))
try {
fn(_this.resolve, _this.reject);
} catch (e) {
_this.reject(e);
}
}
MyPromise.prototype.then = function (onResolved, onRejected) {
let self = this;
// 规范 2.2.7,then 必须返回一个新的 promise
let promise2;
// 规范 2.2.onResolved 和 onRejected 都为可选参数
// 如果类型不是函数需要忽略,同时也实现了透传
// Mypromise.resolve(4).then().then((value) => console.log(value))
onResolved = typeof onResolved === 'function' ? onResolved : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => throw r;
if (self.currentState === RESOLVED) {
return (promise2 = new MyPromise(function (resolve, reject) {
// 规范 2.2.4,保证 onFulfilled,onRjected 异步执行
// 所以用了 setTimeout 包裹下
setTimeout(function () {
try {
let x = onResolved(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (reason) {
reject(reason);
}
});
}));
}
if (self.currentState === REJECTED) {
return (promise2 = new MyPromise(function (resolve, reject) {
setTimeout(function () {
// 异步执行onRejected
try {
let x = onRejected(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (reason) {
reject(reason);
}
});
}));
}
if (self.currentState === PENDING) {
return (promise2 = new MyPromise(function (resolve, reject) {
self.resolvedCallbacks.push(function () {
// 考虑到可能会有报错,所以使用 try/catch 包裹
try {
let x = onResolved(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (r) {
reject(r);
}
});
self.rejectedCallbacks.push(function () {
try {
let x = onRejected(self.value);
resolutionProcedure(promise2, x, resolve, reject);
} catch (r) {
reject(r);
}
});
}));
}
};
// 规范 2.3
function resolutionProcedure(promise2, x, resolve, reject) {
// 规范 2.3.1,x 不能和 promise2 相同,避免循环引用
if (promise2 === x) {
return reject(new TypeError("Error"));
}
// 规范 2.3.2
// 如果 x 为 Mypromise,状态为 pending 需要继续等待否则执行
if (x instanceof MyPromise) {
if (x.currentState === PENDING) {
x.then(function (value) {
// 再次调用该函数是为了确认 x resolve 的
// 参数是什么类型,如果是基本类型就再次 resolve
// 把值传给下个 then
resolutionProcedure(promise2, value, resolve, reject);
}, reject);
} else {
x.then(resolve, reject);
}
return;
}
// 规范 2.3.3.3.3
// reject 或者 resolve 其中一个执行过得话,忽略其他的
let called = false;
// 规范 2.3.3,判断 x 是否为对象或者函数
if (x !== null && (typeof x === "object" || typeof x === "function")) {
// 规范 2.3.3.2,如果不能取出 then,就 reject
try {
// 规范 2.3.3.1
let then = x.then;
// 如果 then 是函数,调用 x.then
if (typeof then === "function") {
// 规范 2.3.3.3
then.call(
x,
y => {
if (called) return;
called = true;
// 规范 2.3.3.3.1
resolutionProcedure(promise2, y, resolve, reject);
},
e => {
if (called) return;
called = true;
reject(e);
}
);
} else {
// 规范 2.3.3.4
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else {
// 规范 2.3.4,x 为基本类型
resolve(x);
}
}
let p=new MyPromise(() => {
console.log('thisis demo')
})
p.then(() => {
console.log('lllee')
})
map,padStart
js
{
console.log(`________________________________________________`)
console.log(`list`.padStart(8, `=`))
let m = [2, 3, 4, 5, 6, 7333].map((x) => x.toString().padStart(10, `*`))
console.log(m)
}
{
console.log(`________________________________________________`)
const cars = {
'🚙BMW': `10`,
'🚘Tesla': `5`,
'🚖Lamborghini': `0`,
}
Object.entries(cars).map(([name, count]) => {
//padEnd appends ' -' until the name becomes 20 characters
//padStart prepends '0' until the count becomes 3 characters.
console.log(`${name.padEnd(20, ` -`)} Count: ${count.padStart(3, `0`)}`)
})
}
{
console.log(`________________________________________________`)
console.log(`list`.padStart(8, `=`))
let m = [2, 3, 4, 5, 6, 7333].map((x) => x.toString().padStart(10, `*`))
console.log(m)
}
{
console.log(`________________________________________________`)
const cars = {
'🚙BMW': `10`,
'🚘Tesla': `5`,
'🚖Lamborghini': `0`,
}
Object.entries(cars).map(([name, count]) => {
//padEnd appends ' -' until the name becomes 20 characters
//padStart prepends '0' until the count becomes 3 characters.
console.log(`${name.padEnd(20, ` -`)} Count: ${count.padStart(3, `0`)}`)
})
}
function
js
// console.log(...[1,2,3,]);
function pushaay(array, items) {
array.push(...items)
console.log(array)
}
pushaay([1, 2], [3, 4, 5]) //[ 1, 2, 3, 4, 5 ]
function f(x, y, z) {
//
}
let args = [1, 2, 3]
f(...args) //不需要apply方法
Math.max(...[23, 5, 12])
let arrbefore = [1, 2, 3]
let arrtemp = [3, 4, 5]
arrbefore.push(...arrtemp)
console.log(...`hello`)
{
let mapa = new Map([
[1, `one`],
[2, `two`],
[3, `three`],
])
let arr = [...mapa.keys()] //[1,2,3]
console.log(`hello\n${arr}`)
}
const go = function* () {
yield 1
yield 2
yield 3
}
let numbers = [...go()] //[1,2,3]
{
let arraylik = { '0': `a`, '1': `b`, '2': `c` }
console.log(Array.from(arraylik))
}
{
Array.from(`hello`) //等同于[...'hello']
let nameset = new Set([`a`, `b`, `1`])
console.log(Array.from(nameset))
}
{
console.log(`________________________________________________`)
console.log(Array.from([1, 3, 4], (x) => x * x))
}
{
console.log(`________________________________________________`)
function typefo() {
return Array.from(arguments, (value) => typeof value) //返回数据类型
}
}
{
console.log(`________________________________________________`)
let nameset = Array.of(2, 3, 4, 5, 6) //[2,3,4,5,6]
console.log(nameset)
}
{
console.log(`________________________________________________`)
let ii = [1, 2, 3, 4, 5].copyWithin(0, 3, 4)
console.log(ii)
}
{
console.log(`________________________________________________`)
function fv(v) {
return v > this.age
}
let person = { name: `json`, age: 20 }
let resp = [12, 45, 23, 11].find(fv, person)
console.log(resp)
}
{
console.log(`________________________________________________`)
const a = [`q`, `b`, `c`].fill(3)
console.log(a)
let arr = new Array(3).fill({ name: `mike` })
arr[0].name = `ben`
console.log(arr) //赋值的是地址
}
{
console.log(`________________________________________________`)
let a = [1, 3, [34, 44]].flat()
console.log(a)
let m = [2, 3, 4].flatMap((x) => [x, x * 2])
console.log(m)
let n = [3, 4, 5].flatMap((x) => [[x * 2]])
console.log(n)
}
{
console.log(`________________________________________________`)
//Array.from();
let arr = Array.from({ '0': 1, '1': 2, length: 2 })
console.log(arr) //[1,2]
;[1, 2, 3, 4, 5].reduce((prev, next, index, current) => {
//prev 如果reduce传入第二个参数,prev为第二个参数;否则prev为数组第一个元素 往后累加
//next 如果reduce传入第二个参数,next为第数组第一个元素;否则next为数组第二个元素 依次累加
//index 函数第几次执行1开始
//current当前数组
return prev + next
})
//reduce方法简单实现
Array.prototype.myReduce = function (cb, pre) {
let prev = pre || this[0]
for (let i = pre ? 0 : 1; i < this.length; i++) {
prev = cb(prev, this[i], i, this)
}
return prev
}
}
{
console.log(`________________________________________________`)
let result = [1, 2, 3, 4, 5].filter(function (item) {
return item > 3
})
console.log(result) //[4,5]
//filter简单实现
Array.prototype.myFilter = function (cb) {
let arr = []
for (let i = 0; i < this.length; i++) {
let item = this[i]
if (cb(item)) arr.push(item)
}
return arr
}
}
// console.log(...[1,2,3,]);
function pushaay(array, items) {
array.push(...items)
console.log(array)
}
pushaay([1, 2], [3, 4, 5]) //[ 1, 2, 3, 4, 5 ]
function f(x, y, z) {
//
}
let args = [1, 2, 3]
f(...args) //不需要apply方法
Math.max(...[23, 5, 12])
let arrbefore = [1, 2, 3]
let arrtemp = [3, 4, 5]
arrbefore.push(...arrtemp)
console.log(...`hello`)
{
let mapa = new Map([
[1, `one`],
[2, `two`],
[3, `three`],
])
let arr = [...mapa.keys()] //[1,2,3]
console.log(`hello\n${arr}`)
}
const go = function* () {
yield 1
yield 2
yield 3
}
let numbers = [...go()] //[1,2,3]
{
let arraylik = { '0': `a`, '1': `b`, '2': `c` }
console.log(Array.from(arraylik))
}
{
Array.from(`hello`) //等同于[...'hello']
let nameset = new Set([`a`, `b`, `1`])
console.log(Array.from(nameset))
}
{
console.log(`________________________________________________`)
console.log(Array.from([1, 3, 4], (x) => x * x))
}
{
console.log(`________________________________________________`)
function typefo() {
return Array.from(arguments, (value) => typeof value) //返回数据类型
}
}
{
console.log(`________________________________________________`)
let nameset = Array.of(2, 3, 4, 5, 6) //[2,3,4,5,6]
console.log(nameset)
}
{
console.log(`________________________________________________`)
let ii = [1, 2, 3, 4, 5].copyWithin(0, 3, 4)
console.log(ii)
}
{
console.log(`________________________________________________`)
function fv(v) {
return v > this.age
}
let person = { name: `json`, age: 20 }
let resp = [12, 45, 23, 11].find(fv, person)
console.log(resp)
}
{
console.log(`________________________________________________`)
const a = [`q`, `b`, `c`].fill(3)
console.log(a)
let arr = new Array(3).fill({ name: `mike` })
arr[0].name = `ben`
console.log(arr) //赋值的是地址
}
{
console.log(`________________________________________________`)
let a = [1, 3, [34, 44]].flat()
console.log(a)
let m = [2, 3, 4].flatMap((x) => [x, x * 2])
console.log(m)
let n = [3, 4, 5].flatMap((x) => [[x * 2]])
console.log(n)
}
{
console.log(`________________________________________________`)
//Array.from();
let arr = Array.from({ '0': 1, '1': 2, length: 2 })
console.log(arr) //[1,2]
;[1, 2, 3, 4, 5].reduce((prev, next, index, current) => {
//prev 如果reduce传入第二个参数,prev为第二个参数;否则prev为数组第一个元素 往后累加
//next 如果reduce传入第二个参数,next为第数组第一个元素;否则next为数组第二个元素 依次累加
//index 函数第几次执行1开始
//current当前数组
return prev + next
})
//reduce方法简单实现
Array.prototype.myReduce = function (cb, pre) {
let prev = pre || this[0]
for (let i = pre ? 0 : 1; i < this.length; i++) {
prev = cb(prev, this[i], i, this)
}
return prev
}
}
{
console.log(`________________________________________________`)
let result = [1, 2, 3, 4, 5].filter(function (item) {
return item > 3
})
console.log(result) //[4,5]
//filter简单实现
Array.prototype.myFilter = function (cb) {
let arr = []
for (let i = 0; i < this.length; i++) {
let item = this[i]
if (cb(item)) arr.push(item)
}
return arr
}
}
from,of
js
{
console.log(`________________________________________________`)
const a1 = Array.of(1, 2, 3)
const a2 = Array(6).fill(12)
console.log(a1, a2)
}
{
console.log(`________________________________________________`)
const m = [1, 2, 3, 4].reduce(
(accumulator, currentValue, currentIndex, array) =>
accumulator * currentValue,
1
)
console.log(m)
}
{
console.log(`________________________________________________`)
const a = [1, 2, 3]
const it = a[Symbol.iterator]()
console.log(it.next().done)
console.log(it.next().value) //1
console.log(it.next().value) //2
console.log(it.next().value)
const findResult = a.includes(1, 0)
console.log(findResult, a.join(`*`))
const b = Array.from(a, (x) => x % 2 === 0)
console.log(b)
}
{
console.log(`________________________________________________`)
const list = [`a`, `b`, `c`]
list.forEach((item, index) => {
console.log(item) //Value
console.log(index) //Index
})
//Index is optional
list.forEach((item) => console.log(item))
}
{
console.log(`________________________________________________`)
const object = {
name: `xiaoming`,
age: 34,
sex: `man`,
}
for (const property in object) {
console.log(property) //Property name
console.log(object[property]) //Property value
}
}
{
console.log(`________________________________________________`)
const age = [16, 14, 18]
const m = age.some((person) => person >= 18)
console.log(m)
}
{
console.log(`________________________________________________`)
const a1 = Array.of(1, 2, 3)
const a2 = Array(6).fill(12)
console.log(a1, a2)
}
{
console.log(`________________________________________________`)
const m = [1, 2, 3, 4].reduce(
(accumulator, currentValue, currentIndex, array) =>
accumulator * currentValue,
1
)
console.log(m)
}
{
console.log(`________________________________________________`)
const a = [1, 2, 3]
const it = a[Symbol.iterator]()
console.log(it.next().done)
console.log(it.next().value) //1
console.log(it.next().value) //2
console.log(it.next().value)
const findResult = a.includes(1, 0)
console.log(findResult, a.join(`*`))
const b = Array.from(a, (x) => x % 2 === 0)
console.log(b)
}
{
console.log(`________________________________________________`)
const list = [`a`, `b`, `c`]
list.forEach((item, index) => {
console.log(item) //Value
console.log(index) //Index
})
//Index is optional
list.forEach((item) => console.log(item))
}
{
console.log(`________________________________________________`)
const object = {
name: `xiaoming`,
age: 34,
sex: `man`,
}
for (const property in object) {
console.log(property) //Property name
console.log(object[property]) //Property value
}
}
{
console.log(`________________________________________________`)
const age = [16, 14, 18]
const m = age.some((person) => person >= 18)
console.log(m)
}
getcount
js
let cars = ['BMW', 'Benz', 'Benz', 'Tesla', 'BMW', 'Toyota']
console.time('测试开发')
let carsObj = cars.reduce(function (obj, name) {
console.log(obj)
console.log(name)
obj[name] = obj[name] ? ++obj[name] : 1
return obj
}, {})
console.log(carsObj) // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
console.timeEnd('测试开发')
let cars = ['BMW', 'Benz', 'Benz', 'Tesla', 'BMW', 'Toyota']
console.time('测试开发')
let carsObj = cars.reduce(function (obj, name) {
console.log(obj)
console.log(name)
obj[name] = obj[name] ? ++obj[name] : 1
return obj
}, {})
console.log(carsObj) // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
console.timeEnd('测试开发')
compress
js
let compress = function (chars) {
let char = chars[0]
let num = 0
let index = 0
let numArr = []
chars.forEach((item) => {
if (item === char) {
num++
} else {
chars[index] = char
if (1 < num && num < 10) {
index++
chars[index] = String(num)
} else if (num >= 10) {
numArr = String(num).split('')
numArr.forEach((n) => {
index++
chars[index] = String(n)
})
}
index++
char = item
num = 1
}
})
chars[index] = char
if (1 < num && num < 10) {
index++
chars[index] = String(num)
} else if (num >= 10) {
numArr = String(num).split('')
numArr.forEach((n) => {
index++
chars[index] = String(n)
})
}
index++
chars.length = index
console.log(chars)
return index
}
let arr = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
console.log(compress(arr))
let compress = function (chars) {
let char = chars[0]
let num = 0
let index = 0
let numArr = []
chars.forEach((item) => {
if (item === char) {
num++
} else {
chars[index] = char
if (1 < num && num < 10) {
index++
chars[index] = String(num)
} else if (num >= 10) {
numArr = String(num).split('')
numArr.forEach((n) => {
index++
chars[index] = String(n)
})
}
index++
char = item
num = 1
}
})
chars[index] = char
if (1 < num && num < 10) {
index++
chars[index] = String(num)
} else if (num >= 10) {
numArr = String(num).split('')
numArr.forEach((n) => {
index++
chars[index] = String(n)
})
}
index++
chars.length = index
console.log(chars)
return index
}
let arr = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
console.log(compress(arr))
reduce
js
let data = {
rows: [
['Lisa', 16, 'Female', '2000-12-01'],
['Bob', 22, 'Male', '1996-01-21'],
],
metaData: [
{
name: 'name',
note: '',
},
{
name: 'age',
note: '',
},
{
name: 'gender',
note: '',
},
{
name: 'birthday',
note: '',
},
],
}
let result = data.rows.reduce(function (prev1, cur1) {
prev1.push(
data.metaData.reduce(function (prev, cur, index) {
prev[cur.name] = cur1[index]
return prev
}, {})
)
return prev1
}, [])
console.log(result)
console.log(result[0])
console.log(result[1])
export {}
let data = {
rows: [
['Lisa', 16, 'Female', '2000-12-01'],
['Bob', 22, 'Male', '1996-01-21'],
],
metaData: [
{
name: 'name',
note: '',
},
{
name: 'age',
note: '',
},
{
name: 'gender',
note: '',
},
{
name: 'birthday',
note: '',
},
],
}
let result = data.rows.reduce(function (prev1, cur1) {
prev1.push(
data.metaData.reduce(function (prev, cur, index) {
prev[cur.name] = cur1[index]
return prev
}, {})
)
return prev1
}, [])
console.log(result)
console.log(result[0])
console.log(result[1])
export {}