简体   繁体   English

在从函数返回的对象上使用 ES6 扩展运算符

[英]Using ES6 spread operator on an object that is returned from a function

I am using a function to convert hex codes to rgb values, it's one I found on this site and all is working perfectly.我正在使用一个函数将十六进制代码转换为 rgb 值,这是我在本网站上找到的一个,并且一切正常。 The function takes in a string as an parameter, and returns an obj with r,g,b properties and their associated values.该函数接受一个字符串作为参数,并返回一个带有r,g,b属性及其关联值的 obj。

I am then taking these values and printing them inside of a React functional component.然后我将这些值打印在 React 功能组件中。 I just wanted to tidy up the syntax and avoid:我只是想整理一下语法并避免:

rgbValue={'rgb=(' + hexToRgb('#000').r + ', ' + hexToRgb('#000').g + ', ' + hexToRgb('#000').b + ')'}

and replace it with something like:并用以下内容替换它:

rgbValue={ 'rgb=(' + ...hexToRgb('#000') + ')'}

Hoping that this would return the r,g,b values from the object and the end result would be:希望这会从对象返回r,g,b值,最终结果是:

rgbValue={'rgb=(0,0,0)'}

However, this is not working as expected.但是,这并没有按预期工作。 I do not know if this is a logic issue or a sytnax error.我不知道这是逻辑问题还是语法错误。 I am new to using the spread operator so I am not overly familiar with it but is there a way to achieve this using my current setup?我是使用扩展运算符的新手,所以我不太熟悉它,但是有没有办法使用我当前的设置来实现这一点?

JS function being used to show what is returned:用于显示返回内容的 JS 函数:

function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  // return rgb values as properties on an object
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

I do not know if this is a logic issue or a sytnax error.我不知道这是逻辑问题还是语法错误。

It's a syntax error.这是一个语法错误。 You can only use spread in the places where spread is defined (that's part of why it's notation/syntax, not an operator).您只能在定义 spread 的地方使用 spread (这就是为什么它是符号/语法,而不是运算符的部分原因)。

If you want to use the result of hexToRgb in string concatenation, you have a few choices:如果你想在字符串连接中使用hexToRgb的结果,你有几个选择:

  1. Have it return a string.让它返回一个字符串。

  2. Have it return an array and call .join(",") on that array;让它返回一个数组并在该数组上调用.join(",") be sure the array is in r, g, b order.确保数组按 r、g、b 顺序排列。

     rgbValue={'rgb=(' + formatRgb(hexToRgb('#000')) + ')'}
  3. Have it return an object (always, not null sometimes) and use Object.values(hexToRgb('#000')).join(",") .让它返回一个对象(总是,有时不为null )并使用Object.values(hexToRgb('#000')).join(",") Be sure the object is created in r, g, b order (yours is), and that this code only runs on a modern JavaScript engine.确保对象是按 r、g、b 顺序创建的(您的顺序是),并且此代码仅在现代 JavaScript 引擎上运行。 The order of object properties was only defined for Object.values very recently (a change that will be in ES2020);对象属性的顺序仅用于定义Object.values最近(的变化,将在ES2020); prior to that, although order existed for some operations, it wasn't required for Object.values and some others.在此之前,尽管某些操作存在顺序,但Object.values和其他一些操作不需要它。 But modern engines already implement the order that was defined, so as long as you don't have to transpile for IE11 or something like that...但是现代引擎已经实现了定义的顺序,所以只要你不必为 IE11 或类似的东西进行转换......

     // See caveats in the text rgbValue={'rgb=(' + Object.values(hexToRgb('#000')).join(",") + ')'}
  4. Have a formatting function you pass the result into有一个格式化函数,你将结果传递给

    rgbValue={'rgb=(' + formatRgb(hexToRgb('#000')) + ')'}

I am not fully grasping this line我没有完全掌握这条线

It's a syntax error.这是一个语法错误。 You can only use spread in the places where spread is defined (that's part of why it's notation/syntax, not an operator).您只能在定义 spread 的地方使用 spread (这就是为什么它是符号/语法,而不是运算符的部分原因)。

But I will look into it.但我会调查一下。

Fair enough, that's a very brief summary of a bit of a complex thing.公平地说,这是对一些复杂事物的非常简短的总结。 Just FWIW:只是 FWIW:

... isn't an operator. ...不是运营商。 An operator has operands (like a function's parameters) and a single result value (like a function's return value) and can be used just about anywhere an expression is expected.运算符具有操作数(如函数的参数)和单个结果值(如函数的返回值),并且几乎可以在任何需要表达式的地方使用。 ... isn't an operator, and can't be, because it doesn't have a single result value. ...不是运算符,也不可能是,因为它没有单个结果值。 Instead, ... is defined as primary syntax with five meanings:相反, ...被定义为具有五种含义的主要语法:

  1. Iterable spread : ... in an array literal or function argument list spreads out an iterable's values as discrete entries for the new array or discrete arguments for the function call. Iterable spread : ...在数组文字或函数参数列表中,将可迭代值作为新数组的离散条目或函数调用的离散参数展开。

 const source = [1, 2, 3, 4]; // In an array literal const dest = [...source, 5, 6]; console.log(dest); // [1, 2, 3, 4, 5, 6] function example1(a, b, c, d) { console.log(a, b, c, d); // 1 2 3 4 } // In a function argument list example1(...source);

  1. Rest parameter : ... before the final declared parameter in a function's parameter list marks the "rest parameter" that will receive all arguments provided from that point on as an array.休息参数: ...在函数参数列表中的最终声明参数之前标记“休息参数”,它将接收从该点开始作为数组提供的所有参数。

 function example2(a, b, ...rest) { console.log(`a = ${a}, b = ${b}, rest = ${JSON.stringify(rest)}`); } example2(1, 2, 3, 4); // a = 1, b = 2, c = [3,4]

  1. Property spread : ... in an object literal spreads out an object's own, enumerable properties a discrete propeties for the object being created. Property spread : ...在对象字面量中,将对象自己的可枚举属性展开为正在创建的对象的离散属性。

 const source = {a: 1, b: 2, c: 3}; const dest = {...source, d: 4, e: 5}; console.log(dest); // {a: 1, b: 2, c: 3, d: 4, e: 5}

  1. Iterable rest (destructuring), the converse of iterable spread in an array literal: ... in an array destructuring pattern marks the target that will receive the "rest" of the iterable entries not consumed by other targets in the pattern (as an array).可迭代剩余(解构),数组文字中可迭代传播的反面: ... )。

 const source = [1, 2, 3, 4]; const [a, b, ...rest] = source; console.log(`a = ${a}, b = ${b}, rest = ${JSON.stringify(rest)}`); // a = 1, b = 2, rest = [3,4]

  1. Property rest (destructuring), the converse of property spread: ... in an object destructuring pattern marks the target that will receive the "rest" of the properties not consumed by other targets in the pattern (as an object).属性剩余(解构),属性传播的反义词: ...在对象解构模式中标记目标,该目标将接收模式中其他目标未消耗的属性的“剩余”(作为对象)。

 const source = {a: 1, b: 2, c: 3}; const {a, ...rest} = source; console.log(a); // 1 console.log(rest); // {b: 2, c: 3}

Outside of those, the meaning of ... is not defined and so it causes a syntax error.除此之外, ...的含义没有定义,因此会导致语法错误。

Return Array instead改为返回数组

function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  // return rgb values as properties on an object
  return result ? [
    parseInt(result[1], 16),
    parseInt(result[2], 16),
    parseInt(result[3], 16)
  ] : [];
}

rgbValue='rgb=(' + hexToRgb('#000').join(',') + ')';
// rgb=(0,0,0)

Firstly, this is an error because the spread operator only works for iterables (eg arrays), not objects (unless you're creating an object).首先,这是一个错误,因为扩展运算符仅适用于可迭代对象(例如数组),而不适用于对象(除非您正在创建对象)。

Secondly, if you were to work around this by converting the object values to an array first, eg ( ...Object.values(myHex) ), this would produce unexpected results since object entries are unordered.其次,如果您首先通过将对象值转换为数组来解决此问题,例如 ( ...Object.values(myHex) ),这将产生意外结果,因为对象条目是无序的。 Ie, there is no guarantee that r would come before g .即,不能保证r会在g之前出现。

IMO, you'r current code is sufficiently clear. IMO,您当前的代码足够清晰。 But if you really want to use the spread operator, you can modify your hexToRgb to return an ordered array result.map(v => parseInt(v, 16))但是如果你真的想使用扩展运算符,你可以修改你的hexToRgb以返回一个有序数组result.map(v => parseInt(v, 16))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM