React js重命名和解构数组长度
React js rename & destructure array length
我有一个像下面这样的 reduce 函数:
let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0);
我试过这样改造,但是好像不是正确的方法:
let el = scopes.reduce ((tot, {actions.length: len}) => tot + len, 0);
有没有办法做到这一点,或者不可能。
你很接近,但你使用嵌套而不是点符号:
// Outer −−−−−−−−−−−−−−−−−−−−v−−−−−−−−−−−−−−−−−−−−−−v
let el = scopes.reduce((tot, {actions: {length: len}}) => tot + len, 0);
// Inner −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−−−−−−−−−−−^
实例:
const scopes = [
{actions: [1, 2, 3]},
{actions: []},
{actions: [4, 5]}
];
let el = scopes.reduce((tot, {actions: {length: len}}) => tot + len, 0);
console.log(el); // 5
关于解构要记住的关键是语法与对象和数组文字相同,包括嵌套;只是信息流向了另一个方向。例如,在对象文字中,数据从右向左流动,从源 (source
) 到目标 (prop
):
let source = 42;
let obj = {prop: source};
// <−−−−−*
在解构中,数据从左向右流动,从源 (prop
) 到目标 (target
):
let {prop: target};
// *−−−−−>
console.log(target); // 42
目标可以是变量、对象属性,甚至是另一种解构模式。这就是我们上面使用的: actions
属性 的目标是解构模式 {length: len}
,它将 length
的值放入变量 len
.这是我的新书中的图 7-1(请参阅我的个人资料以获取链接):
您还可以使用 shorthand 符号并在回调中使用 length
:
let el = scopes.reduce((tot, {actions: {length}}) => tot + length, 0);
实例:
const scopes = [
{actions: [1, 2, 3]},
{actions: []},
{actions: [4, 5]}
];
let el = scopes.reduce((tot, {actions: {length}}) => tot + length, 0);
console.log(el); // 5
我有一个像下面这样的 reduce 函数:
let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0);
我试过这样改造,但是好像不是正确的方法:
let el = scopes.reduce ((tot, {actions.length: len}) => tot + len, 0);
有没有办法做到这一点,或者不可能。
你很接近,但你使用嵌套而不是点符号:
// Outer −−−−−−−−−−−−−−−−−−−−v−−−−−−−−−−−−−−−−−−−−−−v
let el = scopes.reduce((tot, {actions: {length: len}}) => tot + len, 0);
// Inner −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−−−−−−−−−−−^
实例:
const scopes = [
{actions: [1, 2, 3]},
{actions: []},
{actions: [4, 5]}
];
let el = scopes.reduce((tot, {actions: {length: len}}) => tot + len, 0);
console.log(el); // 5
关于解构要记住的关键是语法与对象和数组文字相同,包括嵌套;只是信息流向了另一个方向。例如,在对象文字中,数据从右向左流动,从源 (source
) 到目标 (prop
):
let source = 42;
let obj = {prop: source};
// <−−−−−*
在解构中,数据从左向右流动,从源 (prop
) 到目标 (target
):
let {prop: target};
// *−−−−−>
console.log(target); // 42
目标可以是变量、对象属性,甚至是另一种解构模式。这就是我们上面使用的: actions
属性 的目标是解构模式 {length: len}
,它将 length
的值放入变量 len
.这是我的新书中的图 7-1(请参阅我的个人资料以获取链接):
您还可以使用 shorthand 符号并在回调中使用 length
:
let el = scopes.reduce((tot, {actions: {length}}) => tot + length, 0);
实例:
const scopes = [
{actions: [1, 2, 3]},
{actions: []},
{actions: [4, 5]}
];
let el = scopes.reduce((tot, {actions: {length}}) => tot + length, 0);
console.log(el); // 5