这在javascript中被称为什么? ({name,value})=&gt; <跨度> </跨度>

时间:2016-11-07 16:46:29

标签: javascript syntax ecmascript-6

(在javascript中) 在这方面: const component = ({ name, value }) => <span></span>

箭头函数的第一个参数与其成员分开。 props =&gt; ({ name, value })

这叫什么?我见过有些人跟巴贝尔这样做,但不知道这个名词到底是什么。

2 个答案:

答案 0 :(得分:11)

  

箭头函数的第一个参数与其成员分开。 props => ({ name, value }) ......这叫什么?

它被称为参数解构(有时参数解构,它是解构部分,这很重要)。传递函数的是一个对象,但函数接收的是对象的属性。也就是说,它们已被从结构(对象)中取出并制成不同的东西(因此,“解构”):

const adams = ({question, answer}) => {
  console.log(question);
  console.log(answer);
};
adams({question: "Life, the Unverse, and Everything!", answer: 42});

JavaScript在一些地方进行了解构,包括上面的函数参数列表。您也可以使用作业完成此操作:

const o = {question: "Life, the Unverse, and Everything!", answer: 42};
const {answer, question} = o;
console.log(question);
console.log(answer);

在ES2018及更高版本中有一个相关的功能(但多年来通过传输已在JSX代码中得到支持):将属性“休息”作为对象的能力:

// ES2018+
const adams = ({question, answer, ...rest}) => {
  console.log(question);
  console.log(answer);
  console.log(rest);
};
adams({
  question: "Life, the Unverse, and Everything!",
  answer: 42,
  legend: true,
  missed: true
});

参数列表中...rest内的{}创建一个具有属性“rest”的对象(那些未被捕获为离散参数的对象)。这是JavaScript的“休息参数”的解构版本。您也可以在作业中执行此操作:

// ES2018+
const o = {
  question: "Life, the Unverse, and Everything!",
  answer: 42,
  legend: true,
  missed: true
};
const {question, answer, ...rest} = o;
console.log(question);
console.log(answer);
console.log(rest);

ES2015规范将它用于数组,ES2018为对象属性添加了它。

答案 1 :(得分:0)

它被称为解构。 以下是有关如何使用以及如何使用它的示例:

const employeeOne = { name: 'John', phone: '555-5555', age: 27 };
const { name, phone, age: john_age } = employeeOne;

console.log(name); // 'John'
console.log(phone); // '555-5555'
console.log(john_age); // '27'

sayHi = ({ name }) => console.log(`Hello ${name}, how are you?`);

sayHi(employeeOne); //'Hello John, how are you?'