for (let codePoint of 'foo') {
console.log(codePoint)
}
let greeting = `\`Yo\` World!`;
console.log(greeting);
let greetings=`${{i:5}}`
console.log(greetings);
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`;
const data = [
{ first: '<Jane>', last: 'Bond' },
{ first: 'Lars', last: '<Croft>' },
];
console.log(tmpl(data));
let a = 5;
let b = 10;
function tag(s, v1, v2) {
console.log(s[0]);
console.log(s[1]);
console.log(s[2]);
console.log(v1);
console.log(v2);
return "OK";
}
tag`Hello ${ a + b } world ${ a * b }`;
等同于
tag(['Hello ', ' world ', ''], 15, 50);
let total = 30;
let msg = passthru`The total is ${total} (${total*1.05} with tax)`;
function passthru(literals) {
console.log(literals,arguments);
let result = '';
let i = 0;
while (i < literals.length) {
result += literals[i++];
if (i < arguments.length) {
result += arguments[i];
}
}
return result;
}
console.log(msg);
let sender = '<script>alert("abc")</script>';
let message =
SaferHTML`<p>${sender} has sent you a message.</p>`;
function SaferHTML(templateData) {
let s = templateData[0];
for (let i = 1; i < arguments.length; i++) {
let arg = String(arguments[i]);
s += arg.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
s += templateData[i];
}
return s;
}
console.log(message);
console.log`123`
var s = "𠮷";
s.length
s.charAt(0)
s.charAt(1)
s.charCodeAt(0)
s.charCodeAt(1)
let s = 'Hello world!';
s.startsWith('Hello')
s.endsWith('!')
s.includes('o')
console.log('aabbcc'.replaceAll('b', '_'));
console.log('abbc'.replaceAll('b', '$&'));
console.log('abbc'.replace(/(ab)(bc)/g, '$2$1'));
const str = '123abc456';
const regex = /(\d+)([a-z]+)(\d+)/g;
function replacer(match, p1, p2, p3, offset, string) {
return [p1, p2, p3].join();
}
let a =str.replace(regex, replacer)
console.log(a);
const str = 'hello';
str.at(1)
console.log(str.at(1))
console.log(/^\uD83D/u.test('\uD83D\uDC2A'));
console.log(/^\uD83D/.test('\uD83D\uDC2A'));
var s = '𠮷';
console.log(/^.$/.test(s) );
console.log(/^.$/u.test(s));
/\u{61}/.test('a')
/\u{61}/u.test('a')
/\u{20BB7}/u.test('𠮷')
console.log(Number('0b111'));
console.log(Number.isInteger(25.0));
function throwIfMissing() {
throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
return mustBeProvided;
}
foo('fff')
function doSomething(value = 070) {
'use strict';
return value;
}
const doSomething = (function () {
'use strict';
return function(value = 42) {
return value;
};
}());
console.log((new Function).name);
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
function Timer() {
this.s1 = 0;
this.s2 = 0;
setInterval(() => this.s1++, 1000);
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
function foo() {
return () => {
return () => {
return () => {
console.log('id:', this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()();
var t2 = f().call({id: 3})();
var t3 = f()().call({id: 4});
function foo() {
setTimeout(() => {
console.log('args:', arguments);
}, 100);
}
foo(2, 4, 6, 8)
(function() {
return [
(() => this.x).bind({ x: 'inner' })()
];
}).call({ x: 'outer' });
s = 21;
const obj = {
s: 42,
m: () => console.log(this.s)
};
obj.m()
function Fibonacci2 (n , ac1 = 1 , ac2 = 1) {
if( n <= 1 ) {return ac2};
return Fibonacci2 (n - 1, ac2, ac1 + ac2);
}
Fibonacci2(100)
Fibonacci2(1000)
Fibonacci2(10000)
function currying(fn, n) {
return function (m) {
return fn.call(this, m, n);
};
}
function tailFactorial(n, total) {
if (n === 1) return total;
return tailFactorial(n - 1, n * total);
}
const factorial = currying(tailFactorial, 1);
factorial(5)
function restricted(a,b) {
console.log(restricted.caller);
console.log(restricted.arguments);
}
restricted(1,2);
function sum(x, y) {
if (y > 0) {
return sum(x + 1, y - 1);
} else {
return x;
}
}
sum(1, 100000)
try {
} catch {
}
const arr = [
...(x > 0 ? ['a'] : []),
'b',
];
console.log(arr);
console.log([...'hello']);
Number.prototype[Symbol.iterator] = function*() {
let i = 0;
let num = this.valueOf();
while (i < num) {
yield i++;
}
}
console.log([...5])
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()];
Array.from('hello')
let namesSet = new Set(['a', 'b'])
Array.from(namesSet)
function typesOf () {
return Array.from(arguments, value => typeof value)
}
console.log(typesOf(null, [], NaN));
Array.of(3, 11, 8)
['a', 'b', 'c'].fill(7)
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value);
console.log(entries.next().value);
console.log(entries.next().value);
const contains = (() =>
Array.prototype.includes
? (arr, value) => arr.includes(value)
: (arr, value) => arr.some(el => el === value)
)();
contains(['foo', 'bar'], 'baz');
console.log([1, 2, [3, 4]].flat());
console.log([1, 2, [3, [4, 5]]].flat(2));
console.log([1, 2, , 4, 5].flat());
[2, 3, 4].flatMap((x) => [x, x * 2])
const cart = {
_wheels: 4,
get wheels () {
return this._wheels;
},
set wheels (value) {
if (value < this._wheels) {
throw new Error('数值太小了!');
}
this._wheels = value;
}
}
|