关于输入框非空的判断
在处理输入框相关业务时,往往会判断输入框未输入值的场景。
if(value !== null && value !== undefined && value !== ''){
//...
}
吐槽: ES6中新出的空值合并运算符了解过吗,要写那么多条件吗?
if(value??'' !== ''){
//...
}
// 还可以这样写
objectName ?. [expression]
let server = {
name: 'Server',
// 还可以这样写
'starting up'() {
console.log("The " + this.name + " is starting up!");
}
};
// you can combine the optional chaining operator (?.) with the nullish coalescing operator (??) as follows
let profile = user ?. profile ?? defaultProfile;
// use the optional chaining operator with the method call
functionName ?. (args)
let compressedData = file.compress?.();
// It’s possible to separate the declaration and assignment. However, you must surround the variables in parentheses:
({firstName, lastName} = person);
// 也可以这样
let { firstName, lastName, middleName = '', currentAge: age = 18 } = person;
// The main difference between the `Object.entries()` and the `for...in` loop is
// that the `for...in` loop also enumerates object properties in the prototype chain
const ssn = Symbol('ssn');
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25,
[ssn]: '123-345-789'
};
const kv = Object.entries(person);
console.log(kv);
Code language: JavaScript (javascript)
Output:
[
['firstName', 'John'],
['lastName', 'Doe'],
['age', 25]
]
The hasOwnProperty() method returns true if a property is own
Note that when you import a binding from a module, the binding behaves like it was defined using [const]. It means you can’t have another identifier with the
same name or change the value of the binding.
See the following example:
// greeting.js
export let message = 'Hi';
export function setMessage(msg) {
message = msg;
}
When you import the message variable and setMessage() function, you can use the setMessage() function
to change the value of the message variable as shown below:
// app.js
import {message, setMessage } from './greeting.js';
console.log(message); // 'Hi'
setMessage('Hello');
console.log(message); // 'Hello'
However, you can’t change the value of the message variable directly. The following expression causes an
error:
message = 'Hallo'; // error
Limitation of import and export statements
Note that you must use the import or export statement outside other statements and functions. The following
example causes a SyntaxError:
if( requiredSum ) {
export sum;
}
Because we used the `export` statement inside the `[if]` statement. Similarly, the
following `import` statement also causes a `SyntaxError`:
function importSum() {
import {sum} from './cal.js';
}
Because we used the import statement inside a function.
The reason for the error is that JavaScript must statically determine what will be exported and imported.
Note that ES2020 introduced the function-like object [import()](https://www.javascripttutorial.net/es-
next/javascript-import/) that allows you to dynamically import a module.
https://www.javascripttutorial.net/es-next/javascript-import/
More on the JavaScript import()
If a module has multiple exports, you can use the [object destructuring] to receive the exporting objects.
Suppose the `dialog.js` has two functions:
export function show(message) {
alert(message);
}
export function hide(message) {
console.log('Hide it...');
}
In the app.js, you can use the object destructuring as follows:
let btn = document.querySelector('#show');
btn.addEventListener('click', function () {
(async () => {
try {
// use object destructuring
let {
show,
hide
} = await import('./dialog.js');
// use the functions
show('Hi');
hide();
} catch (err) {
console.log(err);
}
})();
});
Dynamically loading multiple modules
To load multiple modules dynamically, you can use the `[Promise.all()](https://www.javascripttutorial.net/es6/javascript-promise-all/)` method:
Promise.all([
import(module1),
import(module2),
...])
.then(([module1,module2,module3]) => {
// use the modules
});
Accessing the default export
If a module has a default export, you can access it using the default keyword. For example:
import(moduleSpecifier)
.then((module) => {
// access the default export
console.log(module.default);
});
JavaScript Top-level await
https://www.javascripttutorial.net/javascript-top-level-await/
const url = 'https://jsonplaceholder.typicode.com/users';
const response = await fetch(url);
let users = await response.json();
export { users };
----------------------------------------------------------------
let module;
try {
module = await import('https://cdn1.com/module');
} catch {
module = await import('https://cdn2.com/module');
}
--------------------------------------------------------------------
const words = await import(`/i18n/${navigator.language}`);
console.log(Symbol() === Symbol()); // false
--------------------------------------------------------------------
let firstName = Symbol('first name'),
lastName = Symbol('last name');
console.log(firstName); // Symbol(first name)
console.log(lastName); // Symbol(last name)
--------------------------------------------------------------------
Since symbols are primitive values, you can use the typeof operator to check whether a variable is a
symbol. ES6 extended typeof to return the symbol string when you pass in a symbol variable:
console.log(typeof firstName); // symbol
--------------------------------------------------------------------
Since a symbol is a primitive value, if you attempt to create a symbol using the new operator, you will get an
error:
let s = new Symbol(); // error
--------------------------------------------------------------------
ES6 provides you with a global symbol registry that allows you to share symbols globally. If you want to
create a symbol that will be shared, you use the Symbol.for() method instead of calling the Symbol() function.
The Symbol.for() method accepts a single parameter that can be used for symbol’s description, as shown in
the following example:
let ssn = Symbol.for('ssn');
let citizenID = Symbol.for('ssn');
console.log(ssn === citizenID); // true
console.log(Symbol.keyFor(citizenID)); // 'ssn'
let systemID = Symbol('sys');
console.log(Symbol.keyFor(systemID)); // undefined
--------------------------------------------------------------------
You can use symbols as names. See the following example:
let status = Symbol('status');
let task = {
[status]: statuses.OPEN,
description: 'Learn ES6 Symbol'
};
console.log(task);`
To get all the enumerable properties of an object, you use the `Object.keys()` method.
`console.log(Object.keys(task)); // ["description"]`
To get all properties of an object whether the properties are enumerable or not, you use
the `Object.getOwnPropertyNames()` method.
`console.log(Object.getOwnPropertyNames(task)); // ["description"]`
To get all property symbols of an object, you use the `Object.getOwnPropertySymbols()` method, which has
been added in ES6.
`console.log(Object.getOwnPropertySymbols(task)); //[Symbol(status)]`
The `Object.getOwnPropertySymbols()` method returns an array of own property symbols from an object.
let userRoles = new Map();
The userRoles is an instance of the Map object and its type is an object as illustrated in the following example:
console.log(typeof(userRoles)); // object
console.log(userRoles instanceof Map); // true
userRoles.set(john, 'admin');
------------------------------------------------------------------------------------
As mentioned earlier, you can pass an iterable object to the Map() constructor:
let userRoles = new Map([
[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber']
]);
userRoles.get(john); // admin
If you pass a key that does not exist, the get() method will return undefined.
let foo = {name: 'Foo'};
userRoles.get(foo); //undefined
To check if a key exists in the map, you use the has() method.
userRoles.has(foo); // false
userRoles.has(lily); // true
The size property returns the number of entries of the Map object.
console.log(userRoles.size); // 3
-----------------------------------------------------------
let john = { name: 'John Doe' },
lily = { name: 'Lily Bush' },
peter = { name: 'Peter Drucker' };
let userRoles = new Map([
[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber'],
]);
for (const user of userRoles.keys()) {
console.log(user.name);
}
Code language: JavaScript (javascript)
Output:
John Doe
Lily Bush
Peter Drucker
------------------------------------------
Iterate over map values
Similarly, you can use the values() method to get an iterator object that contains values for all the elements in the map:
let john = { name: 'John Doe' },
lily = { name: 'Lily Bush' },
peter = { name: 'Peter Drucker' };
let userRoles = new Map([
[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber'],
]);
for (let role of userRoles.values()) {
console.log(role);
}
Code language: JavaScript (javascript)
Output:
admin
editor
subscriber
----------------------------------------------------------------------------
Iterate over map elements
Also, the entries() method returns an iterator object that contains an array of [key,value] of each element in the Map object:
let john = { name: 'John Doe' },
lily = { name: 'Lily Bush' },
peter = { name: 'Peter Drucker' };
let userRoles = new Map([
[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber'],
]);
for (const role of userRoles.entries()) {
console.log(`${role[0].name}: ${role[1]}`);
}
-------------------------------------------------------------------------------
Delete an element by key
To delete an entry in the map, you use the delete() method.
userRoles.delete(john);
Code language: CSS (css)
Delete all elements in the map
To delete all entries in the Map object, you use the clear() method:
userRoles.clear();
Code language: CSS (css)
Hence, the size of the map now is zero.
console.log(userRoles.size); // 0
-------------------------------------------------------------------------------
WeakMap
A WeakMap is similar to a Map except the keys of a WeakMap must be objects. It means that when a reference to a key (an object) is out of scope, the corresponding value is automatically released from the memory.
A WeakMap only has subset methods of a Map object:
get(key)
set(key, value)
has(key)
delete(key)
Here are the main difference between a Map and a WeekMap:
- Elements of a WeakMap cannot be iterated.
- Cannot clear all elements at once.
- Cannot check the size of a WeakMap.
In this tutorial, you have learned how to work with the JavaScript Map object and its useful methods to manipulate entries in the map.
https://www.javascripttutorial.net/javascript-try-catch-finally/
try…catch…finally and return
The finally block always executes whether exceptions occur or not. Also, you can do nothing to prevent it from executing including using a return statement. For example:
function fn() {
try {
return 1;
} catch {
return 2;
} finally {
return 3;
}
}
console.log(fn());
Code language: JavaScript (javascript)
Output:
3
In this example, the return statement in the try block returns 1. Hence, the fn() function should have returned 1. However, it is not the case.
Because the finally block always executes, the return statement in the finally block returns 3. Therefore, the fn() function returns 3.
In other words, the return statements in the try and catch blocks are ignored in the try...catch...finally statement.
https://www.javascripttutorial.net/javascript-variable-scope/
Global variable leaks: the weird part of JavaScript
See the following example:
function getCounter() {
counter = 10;
return counter;
}
console.log(getCounter());
Code language: JavaScript (javascript)
Output:
10
In this example, we assigned 10 to the counter variable without the var, let, or const keyword and then returned it.
Outside the function, we called the getCounter() function and showed the result in the console.
This issue is known as the leaks of the global variables.
Under the hood, the JavaScript engine first looks up the counter variable in the local scope of the getCounter() function. Because there is no var, let, or const keyword, the counter variable is not available in the local scope. It hasn’t been created.
Then, the JavaScript engine follows the scope chain and looks up the counter variable in the global scope. The global scope also doesn’t have the counter variable, so the JavaScript engine creates the counter variable in the global scope.
To fix this “weird” behavior, you use the 'use strict' at the top of the script or at the top of the function:
'use strict'
function getCounter() {
counter = 10;
return counter;
}
console.log(getCounter());
Code language: JavaScript (javascript)
Now, the code throws an error:
ReferenceError: counter is not defined
Code language: JavaScript (javascript)
The following shows how to use the 'use strict' in the function:
function getCounter() {
'use strict'
counter = 10;
return counter;
}
console.log(getCounter());
function getUser(userId) {
return new Promise((resolve, reject) => {
console.log('Get the user from the database.');
setTimeout(() => {
resolve({
userId: userId,
username: 'admin'
});
}, 1000);
})
}
function getServices(user) {
return new Promise((resolve, reject) => {
console.log(`Get the services of ${user.username} from the API.`);
setTimeout(() => {
resolve(['Email', 'VPN', 'CDN']);
}, 3 * 1000);
});
}
function getServiceCost(services) {
return new Promise((resolve, reject) => {
console.log(`Calculate the service cost of ${services}.`);
setTimeout(() => {
resolve(services.length * 100);
}, 2 * 1000);
});
}
Code language: JavaScript (javascript)
The following uses the promises to serialize the sequences:
getUser(100)
.then(getServices)
.then(getServiceCost)
.then(console.log);
Code language: CSS (css)
Output
Get the user from the database.
Get the services of admin from the API.
Calculate the service cost of Email,VPN,CDN.
300
The Promise.all() returns a Promise that is rejected if any of the input promises are rejected.
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The second promise has rejected');
reject('Failed');
}, 2 * 1000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The third promise has resolved');
resolve(30);
}, 3 * 1000);
});
Promise.all([p1, p2, p3])
.then(console.log) // never execute
.catch(console.log);
Code language: JavaScript (javascript)
Output:
The first promise has resolved
The second promise has rejected
Failed
The third promise has resolved
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The second promise has resolved');
resolve(20);
}, 2 * 1000);
});
Promise.race([p1, p2])
.then(value => console.log(`Resolved: ${value}`))
.catch(reason => console.log(`Rejected: ${reason}`));
Code language: JavaScript (javascript)
Output:
The first promise has resolved
Resolved: 10
The second promise has resolved
这个是真的有点niubility,这不就是苹果使用的那个优化方法吗
// after 0.5 seconds, if the getData() has not resolved, then show
// the Loading indicator
const TIMEOUT = 500;
const DATA_LOAD_TIME = 5000;
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const message = 'Promise.race() Demo';
resolve(message);
}, DATA_LOAD_TIME);
});
}
function showContent(message) {
document.querySelector('#message').textContent = message;
}
function timeout() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(), TIMEOUT);
});
}
function showLoadingIndicator() {
document.querySelector('#loader').className = 'loader';
}
function hideLoadingIndicator() {
document.querySelector('#loader').className = '';
}
// handle button click event
const btn = document.querySelector('#btnGet');
btn.addEventListener('click', () => {
// reset UI if users click the second time
reset();
// show content or loading indicator
Promise.race([getData()
.then(showContent)
.then(hideLoadingIndicator), timeout()
])
.catch(showLoadingIndicator);
});
// reset UI
function reset() {
hideLoadingIndicator();
showContent('');
}
https://www.javascripttutorial.net/es-next/javascript-promise-any/
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 1 rejected');
reject('error');
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 2 fulfilled');
resolve(2);
}, 2000);
});
const p = Promise.any([p1, p2]);
p.then((value) => {
console.log('Returned Promise');
console.log(value);
});
Code language: JavaScript (javascript)
Output:
Promise 1 rejected
Promise 2 fulfilled
Returned Promise
2
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 1 rejected');
reject('error1');
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 2 rejected');
reject('error2');
}, 2000);
});
const p = Promise.any([p1, p2]);
p.catch((e) => {
console.log('Returned Promise');
console.log(e, e.errors);
});
Code language: JavaScript (javascript)
Output:
Promise 1 rejected
Promise 2 rejected
Returned Promise
[AggregateError: All promises were rejected] [ 'error1', 'error2' ]
To access the index of the array elements inside the loop, you can use the `for...of` statement with the `entries()` method of the array.
The `array.entries()` method returns a pair of `[index, element]` in each iteration. For example:
<pre class="wp-block-code" aria-describedby="shcb-language-4" data-shcb-language-name="JavaScript" data-shcb-language-slug="javascript" style="font-family: monospace, monospace; font-size: 16px; position: relative; border: 0px; padding: 0px; color: rgb(33, 37, 41); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
`let colors = ['Red', 'Green', 'Blue'];
for (const [index, color] of colors.entries()) {
console.log(`${color} is at index ${index}`);
}`
<small class="shcb-language" id="shcb-language-4" style="font-size: 12.8px; border: 0px; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; overflow-wrap: normal; word-break: normal;">Code language: JavaScript (javascript)</small></pre>
Output:
<pre class="wp-block-code" style="font-family: monospace, monospace; font-size: 16px; position: relative; border: 0px; padding: 0px; color: rgb(33, 37, 41); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
`Red is at index 0
Green is at index 1
Blue is at index 2`
</pre>
In this example, we used the [array destructuring ](https://www.javascripttutorial.net/es6/destructuring/)to assign the result of the `entries()` method to the `index` and `color` variables in each iteration:
<pre class="wp-block-code" aria-describedby="shcb-language-5" data-shcb-language-name="CSS" data-shcb-language-slug="css" style="font-family: monospace, monospace; font-size: 16px; position: relative; border: 0px; padding: 0px; color: rgb(33, 37, 41); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
`const [index, color] of colors.entries()`
<small class="shcb-language" id="shcb-language-5" style="font-size: 12.8px; border: 0px; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; overflow-wrap: normal; word-break: normal;">Code language: CSS (css)</small></pre>
### 2) In-place object destructuring with for…of
Consider the following example:
<pre class="wp-block-code" aria-describedby="shcb-language-6" data-shcb-language-name="JavaScript" data-shcb-language-slug="javascript" style="font-family: monospace, monospace; font-size: 16px; position: relative; border: 0px; padding: 0px; color: rgb(33, 37, 41); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
`const ratings = [
{user: 'John',score: 3},
{user: 'Jane',score: 4},
{user: 'David',score: 5},
{user: 'Peter',score: 2},
];
let sum = 0;
for (const {score} of ratings) {
sum += score;
}
console.log(`Total scores: ${sum}`); // 14`
<small class="shcb-language" id="shcb-language-6" style="font-size: 12.8px; border: 0px; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; overflow-wrap: normal; word-break: normal;">Code language: JavaScript (javascript)</small></pre>
Output:
<pre class="wp-block-code" style="font-family: monospace, monospace; font-size: 16px; position: relative; border: 0px; padding: 0px; color: rgb(33, 37, 41); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
`Total scores: 14`
</pre>
const user = {
firstName: 'John',
lastName: 'Doe'
}
const getFullName = function (user) {
return `${user.firstName} ${user.lastName}`;
}
const getFullNameProxy = new Proxy(getFullName, {
apply(target, thisArg, args) {
return target(...args).toUpperCase();
}
});
console.log(getFullNameProxy(user)); //
Code language: JavaScript (javascript)
Output
JOHN DOE
let person = {
name: 'John',
age: 25,
};
function increaseAge(obj) {
obj.age += 1;
}
increaseAge(person);
console.log(person);
{name: 'John', age: 26}
age : 26
name : "John"
let person = {
name: 'John',
age: 25,
};
function increaseAge(obj) {
obj.age += 1;
// reference another object
obj = { name: 'Jane', age: 22 };
}
increaseAge(person);
console.log(person);
{ name: 'John', age: 26 }
const params = 'type=listing&page=2&rowCount=10';
const searchParams = new URLSearchParams(params);
console.log(Object.fromEntries(searchParams));
Output:
{type: "listing", page: "2", rowCount: "10"}
-------------------------------------------------------------------------------------------------
const config = new Map();
config.set('type', 'database');
config.set('duration', 30);
const cache = Object.fromEntries(config);
console.log(cache);
Code language: JavaScript (javascript)
Output:
{type: "database", duration: 30}
-------------------------------------------------------------------------------------------------
const arr = [
['firstName', 'John'],
['lastName', 'Doe'],
['age', 20]
];
const person = Object.fromEntries(arr);
console.log(person);
Code language: JavaScript (javascript)
Output:
{firstName: "John", lastName: "Doe", age: 20}
const numbers = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];
const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers);
[1, 2, 3, 4, 5, 6, 7, 8, 9]
-------------------------------------------------------------
const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);
console.log(flatNumbers);
Code language: JavaScript (javascript)
Output:
[1, 2, 3, 4, 5, 6, 7]
------------------------------------------------------------------------------------------------------------------------
const numbers = [1, 2, [3, 4, 5]];
const flatNumbers = numbers.flat();
console.log(flatNumbers);
Code language: JavaScript (javascript)
Output:
[1, 2, 3, 4, 5]
let sentences = [
"JavaScript Array flatMap()",
" ",
"is",
" ",
"Awesome"
];
let words = sentences.flatMap(s => s.split(' '));
console.log(words);
Code language: JavaScript (javascript)
Output:
[ 'JavaScript', 'Array', 'flatMap()', '', '', 'is', '', '', 'Awesome' ]
-------------
let cart = [{
name: 'Smartphone',
qty: 2,
price: 500,
freeOfCharge: false
},
{
name: 'Tablet',
qty: 1,
price: 800,
freeOfCharge: false
}
];
If customers buy a smartphone, you want to give them a free screen protector.
When the customer adds a smartphone to the cart, you can add a screen protector to the cart using the `flatMap()` method as follows:
let newCart = cart.flatMap(
(item) => {
if (item.name === 'Smartphone') {
return [item, {
name: 'Screen Protector',
qty: item.qty,
price: 5,
freeOfCharge: true
}]
} else {
return [item];
}
}
);
console.log(newCart);
The cart will look like this:
[
{ name: 'Smartphone', qty: 2, price: 500, freeOfCharge: false },
{ name: 'Screen Protector', qty: 2, price: 5, freeOfCharge: true },
{ name: 'Tablet', qty: 1, price: 800, freeOfCharge: false }
]
The following uses the `[reduce()](https://www.javascripttutorial.net/javascript-array-reduce/)` method to calculate the total amount from the items in the cart. It ignores the free-of-charge items, like screen protectors:
const total = newCart.reduce((sum, item) => {
if (!item.freeOfCharge)
sum += item.price * item.qty;
return sum;
}, 0);
console.log({total});
{ total: 1800 }
let user = {
username: 'Satoshi'
};
user.nickname ??= 'anonymous';
console.log(user);
Code language: JavaScript (javascript)
Output:
{username: 'Satoshi', nickname:'anonymous'}
---------------------------------------------------------------------------------
let person = {
firstName: 'Jane',
lastName: 'Doe',
};
person.lastName &&= 'Smith';
console.log(person);
Code language: JavaScript (javascript)
Output:
{firstName: 'Jane', lastName: 'Smith'}
------------------------------------------------------------------------------------
let title = 'JavaScript Awesome';
title ||= 'untitled';
console.log(title);
Code language: JavaScript (javascript)
Output:
'JavaScript Awesome'
const scores = [5, 6, 7];
console.log(scores.at(1)); // same as scores[1]
// get the last element
console.log(scores.at(-1)); // 7
console.log(scores.at(-1) === scores[scores.length - 1]); // true
Code language: JavaScript (javascript)
Output:
6
7
true
网友评论