解构并将值重命名为字符串键

时间:2019-10-09 18:02:23

标签: javascript ecmascript-6

任何方式我都可以做这样的事情吗?我需要值的特定名称...

<svg viewBox="0 0 400 100"  width="400px" height="100px">
  <rect x="0" y="0" width="400" height="100" stroke="red" stroke-width="3px" fill="white"/>
  <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Hello World</text>    
</svg>

3 个答案:

答案 0 :(得分:1)

变量名称不能包含连字符(-),因此您不能包含连字符。

但是,只要它们的名称是有效的标识符,您仍然可以重命名已分解的属性:

const {
  firstNm: my_funny_first_name,
  lastNm: bar_foo_Bar
} = response;

请注意,您不能引用这些名称,但完全不需要:

  • 有效的标识符名称可以不带引号,并且
  • 在该位置不允许使用无效的标识符名称。

答案 1 :(得分:0)

您可以执行此操作,但是您需要使用有效的变量名,并且可以省略引号。换句话说:

# Script block to initialize the arrays.
# The filler arrays are randomized to eliminate caching effects in LINQ.
$init = {
  $fillerArray = 1..1000 | Get-Random -Count 1000
  [string[]] $ItemArray = $fillerArray + 'a' + $fillerArray + 'b' + $fillerArray + 'c' + $fillerArray + 'd'
  [string[]] $exclusionArray = $fillerArray + 'b' + $fillerArray + 'c'
}

# Compare the average of 10 runs.
Time-Command -Count 10 { # LINQ
  . $init
  $result = [string[]] [Linq.Enumerable]::Except($ItemArray, $exclusionArray)
}, { # Where ... -notContains
  . $init
  $result = $ItemArray.Where({ $exclusionArray -notcontains $_ })
}

^这将创建新的变量const { firstNm: myFunnyFirstName, lastNm: barFooBar } = response myFunnyFirstName分别代表barFooBarresponse.firstNm

答案 2 :(得分:0)

您需要将my-funny-first-name更改为myFunnyFirstName,因为变量名中不能包含破折号。

var response = {
  "firstNm" : "Billy-Bob",
  "lastNm"  : "Foo Bar"
};

const {
  firstNm: myFunnyFirstName,
  lastNm: barFooBar
} = response;

console.log(`myFunnyFirstName = ${myFunnyFirstName}\nbarFooBar = ${barFooBar}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }